Add JavaScript object to JavaScript object - javascript

I'd like to have JavaScript objects within another JavaScript object as such:
Issues:
- {"ID" : "1", "Name" : "Missing Documentation", "Notes" : "Issue1 Notes"}
- {"ID" : "2", "Name" : "Software Bug", "Notes" : "Issue2 Notes, blah, blah"}
- {"ID" : "2", "Name" : "System Not Ready", "Notes" : "Issue3 Notes, etc"}
// etc...
So, I'd like "Issues" to hold each of these JavaScript objects, so that I can just say Issues[0].Name, or Issues[2].ID, etc.
I've created the outer Issues JavaScript object:
var jsonIssues = {};
I'm to the point where I need to add a JavaScript object to it, but don't know how. I'd like to be able to say:
Issues<code here>.Name = "Missing Documentation";
Issues<code here>.ID = "1";
Issues<code here>.Notes = "Notes, notes notes";
Is there any way to do this? Thanks.
UPDATE: Per answers given, declared an array, and am pushing JavaScript objects on as needed:
var jsonArray_Issues = new Array();
jsonArray_Issues.push( { "ID" : id, "Name" : name, "Notes" : notes } );
Thanks for the responses.

var jsonIssues = []; // new Array
jsonIssues.push( { ID:1, "Name":"whatever" } );
// "push" some more here

As my first object is a native JavaScript object (used like a list of objects), push didn't work in my scenario, but I resolved it by adding new key as follows:
MyObjList['newKey'] = obj;
In addition to this, may be useful to know how to delete the same object as inserted before:
delete MyObjList['newKey'][id];
Hope it helps someone as it helped me.

var jsonIssues = [
{ID:'1',Name:'Some name',Notes:'NOTES'},
{ID:'2',Name:'Some name 2',Notes:'NOTES 2'}
];
If you want to add to the array then you can do this
jsonIssues[jsonIssues.length] = {ID:'3',Name:'Some name 3',Notes:'NOTES 3'};
Or you can use the push technique that the other guy posted, which is also good.

// Merge object2 into object1, recursively
$.extend( true, object1, object2 );
// Merge object2 into object1
$.extend( object1, object2 );
https://api.jquery.com/jquery.extend/

If it's not an array of object you can do this:
let student= {
name : 'Mr. Anderson',
id: 35
}
student['grade'] = 10; //for a property.
Result:
student= {
name : 'Mr. Anderson',
id: 35,
grade:10
}
You also can add an object:
let student= {
personalData:{
//personal data key-value
}
}
let academicData = {
//academic data key-value
}
student['academicData'] = academicData;
Result:
student{
personalData{},
academicData{}
}

jsonIssues = [...jsonIssues,{ID:'3',Name:'name 3',Notes:'NOTES 3'}]

If you have properties in first obj and you have to add your objs to it, then Object.assign() will erase it.
To avoid this loss I've written a function below. Be aware, it copies nested objs by refference.
First you should add all objs you want to add to your's obj to an arr. You can do it easily by arr.push(). Then just use the Fn.
function addMyObjs (objInit, arrWithObjs) {
let map = new Map();
for (let [key, value] of Object.entries(objInit)) {
map.set(key, value);
}
arrWithObjs.forEach((item) => {
for (let [key, value] of Object.entries(item)) {
map.set(key, value);
}
});
return Object.fromEntries(map);
}
let objSecond = {id: 2,};
let obj = {
name: "Tolya",
age: 33,
sex: "man",
};
let obj3 = {"fruits": {"apples": true, "plums": false,}};
let arr = [obj, obj3];
objSecond = addMyObjs(objSecond, arr);

Related

How can I push an object into an array?

I know it's simple, but I don't get it.
I have this code:
// My object
const nieto = {
label: "Title",
value: "Ramones"
}
let nietos = [];
nietos.push(nieto.label);
nietos.push(nieto.value);
If I do this I'll get a simple array:
["Title", "Ramones"]
I need to create the following:
[{"01":"Title", "02": "Ramones"}]
How can I use push() to add the object into the nietos array?
You have to create an object. Assign the values to the object. Then push it into the array:
var nietos = [];
var obj = {};
obj["01"] = nieto.label;
obj["02"] = nieto.value;
nietos.push(obj);
Create an array of object like this:
var nietos = [];
nietos.push({"01": nieto.label, "02": nieto.value});
return nietos;
First you create the object inside of the push method and then return the newly created array.
can be done like this too.
// our object array
let data_array = [];
// our object
let my_object = {};
// load data into object
my_object.name = "stack";
my_object.age = 20;
my_object.hair_color = "red";
my_object.eye_color = "green";
// push the object to Array
data_array.push(my_object);
Using destructuring assignment (ES6)
const nieto = {label: 'title', value: 'ramones' }
const modifiedObj = {01: nieto.label, 02: nieto.value}
let array = [
{03: 'asd', 04: 'asd'},
{05: 'asd', 06: 'asd'}
]
// push the modified object to the first index of the array
array = [modifiedObj, ...array]
console.log(array)
If you'd like to push the modified object to the last index of the array just change the destructured array ...array to the front.
array = [...array, modifiedObj]
Well, ["Title", "Ramones"] is an array of strings. But [{"01":"Title", "02", "Ramones"}] is an array of object.
If you are willing to push properties or value into one object, you need to access that object and then push data into that.
Example:
nietos[indexNumber].yourProperty=yourValue; in real application:
nietos[0].02 = "Ramones";
If your array of object is already empty, make sure it has at least one object, or that object in which you are going to push data to.
Let's say, our array is myArray[], so this is now empty array, the JS engine does not know what type of data does it have, not string, not object, not number nothing. So, we are going to push an object (maybe empty object) into that array. myArray.push({}), or myArray.push({""}).
This will push an empty object into myArray which will have an index number 0, so your exact object is now myArray[0]
Then push property and value into that like this:
myArray[0].property = value;
//in your case:
myArray[0]["01"] = "value";
I'm not really sure, but you can try some like this:
var pack = function( arr ) {
var length = arr.length,
result = {},
i;
for ( i = 0; i < length; i++ ) {
result[ ( i < 10 ? '0' : '' ) + ( i + 1 ) ] = arr[ i ];
}
return result;
};
pack( [ 'one', 'two', 'three' ] ); //{01: "one", 02: "two", 03: "three"}
The below solution is more straight-forward. All you have to do is define one simple function that can "CREATE" the object from the two given items. Then simply apply this function to TWO arrays having elements for which you want to create object and save in resultArray.
var arr1 = ['01','02','03'];
var arr2 = ['item-1','item-2','item-3'];
resultArray = [];
for (var j=0; j<arr1.length; j++) {
resultArray[j] = new makeArray(arr1[j], arr2[j]);
}
function makeArray(first,second) {
this.first = first;
this.second = second;
}
This solution can be used when you have more than 2 properties in any object.
const nieto = {
label: "Title",
value: "Ramones"
}
let nietos = [];
let xyz = Object.entries(nieto)
xyz.forEach((i,j)=>{
i[0] = `${(j+1).toLocaleString("en-US", {
minimumIntegerDigits: 2,
useGrouping: false,
})}`
})
nietos.push(Object.fromEntries(xyz))

Uncaught TypeError: data.push is not a function

I am trying to push
data.push({"country": "IN"});
as new id and value to a json string. but it gives the following error
Uncaught TypeError: data.push is not a function
data{"name":"ananta","age":"15"}
Advance Thanks for your reply
To use the push function of an Array your var needs to be an Array.
Change data{"name":"ananta","age":"15"} to following:
var data = [
{
"name": "ananta",
"age": "15",
"country": "Atlanta"
}
];
data.push({"name": "Tony Montana", "age": "99"});
data.push({"country": "IN"});
..
The containing Array Items will be typeof Object and you can do following:
var text = "You are " + data[0]->age + " old and come from " + data[0]->country;
Notice: Try to be consistent. In my example, one array contained object properties name and age while the other only contains country. If I iterate this with for or forEach then I can't always check for one property, because my example contains Items that changing.
Perfect would be: data.push({ "name": "Max", "age": "5", "country": "Anywhere" } );
So you can iterate and always can get the properties, even if they are empty, null or undefined.
edit
Cool stuff to know:
var array = new Array();
is similar to:
var array = [];
Also:
var object = new Object();
is similar to:
var object = {};
You also can combine them:
var objectArray = [{}, {}, {}];
Your data variable contains an object, not an array, and objects do not have the push function as the error states. To do what you need you can do this:
data.country = 'IN';
Or
data['country'] = 'IN';
Also make sure that the name of the variable is not some kind of a language keyword.
For instance, the following produces the same type of error:
var history = [];
history.push("what a mess");
replacing it for:
var history123 = [];
history123.push("pray for a better language");
works as expected.
you can use push method only if the object is an array:
var data = new Array();
data.push({"country": "IN"}).
OR
data['country'] = "IN"
if it's just an object you can use
data.country = "IN";
I think you set it as
var data = [];
but after some time you made it like:
data = 'some thing which is not an array';
then
data.push('') will not work as it is not an array anymore.
One things to remember push work only with array[] not object{}.
If you want to add object o inside inside n like that :
a = {
b:"c",
D:"e",
F: {
g:"h",
I:"j",
k: {
l:"m"
}
}
}
a.F.k.n = { o: "p" };
console.log(a);
Try This Code $scope.DSRListGrid.data = data; this one for source data
for (var prop in data[0]) {
if (data[0].hasOwnProperty(prop)) {
$scope.ListColumns.push(
{
"name": prop,
"field": prop,
"width": 150,
"headerCellClass": 'font-12'
}
);
}
}
console.log($scope.ListColumns);
make sure you push into an Array only
and if their is error like Uncaught TypeError: data.push is not a function**
then check for type of data
you can do this by consol.log(data)
hope this will help
let dataArray = [{'id':1,'code':'ABC'},{'id':1,'code':'ABC'},{'id':2,'code':'ABC'}]
let obj = {};
dataArray.forEach(task => {
task.id in obj ? obj[task.employee_id].push(task):
obj = {
...obj,
[task.employee_id]: [task],
}
});

Replace/change item with same key

Using underscore and I have an object array like so -
myObj = [{"car" : "red" },{"tree" : "green"}];
and I am being passed a new object that I need to find and overwrite an object with the same key, so I would be sent like
{"car" : "blue" };
And I have to take the original object and change the car to blue. Is this possible with underscore? Thanks!
Edit - just to be clear, I am being given the {"car" : "blue"} and I need to compare it to the original object and find the "car" and replace it with the new value. Thanks!
Sure. Assuming all of your objects only have one key:
var myArr = [ { "car" : "red" }, { "tree": "green" } ];
// First, find out the name of the key you're going to replace
var newObj = { "car": "blue" };
var newObjKey = Object.keys(newObj)[0]; // => "car"
// Next, get the index of the array item that has the key
var index = _.findIndex(myArr, function(obj) { return newObjKey in obj; });
// => 0
// Finally, replace the value
myArr[index][newObjKey] = newObj[newObjKey];
FYI findIndex is an Underscore.js 1.8 feature. If you're using an older version of Underscore, you'll need to replace that line with something like this:
var index;
_.find(myObj, function(obj, idx) {
if("car" in obj) {
index = idx;
return true;
}
});
another way you can do this would be as follows
myObj = [{"car" : "red" },{"tree" : "green"}];
let object2 = {"car": "blue"}
for(let obj of myObj){
for(let key in obj){
object2[key] ? obj[key] = object2[key] : ''
}
}
That should dynamically replace anything from object2 which matches a key in an object within the array myObj
don't need any extra libraries or crazy variables :) Just good old fashioned javascript
EDIT Might not be a bad idea to include something like if(object2 && Object.keys(object2)){} around the for loop just to ensure that the object2 isn't empty/undefined

In Javascript, how can I Rename/Renumber a set of properties?

This is one of those questions I'm ashamed to even ask, but I'm working with an external JSON source and I'm forced to do something ugly. So here goes...
I have 'dirty' Javascript object, with property names containing a number at their end:
{ "Friend1" : "Bob",
"Friend6" : "Fred",
"Friend632" : "Gonzo",
"FriendFinder1" : "Dolly",
"FriendFinder4294" : "Jan"
}
I'm trying to figure out a way to clean-up/"zero-index" these property names so the object would look like:
{ "Friend0" : "Bob",
"Friend1" : "Fred",
"Friend2" : "Gonzo",
"FriendFinder0" : "Dolly",
"FriendFinder1" : "Jan"
}
I'm referencing this indexOf/Regex code:
Is there a version of JavaScript's String.indexOf() that allows for regular expressions?
Any strategies you could recommend for doing this? I'll post where I'm at in a bit. Many thanks!
Take the "base" of a key and append items with a common base to an array using the original index. (This produces a sparse array.) Then stretch it out again by enumerating each item with a common base into a new key with 'base'+enumeratedindex.
The trick here is to use a method like forEach to enumerate the array--this will only visit assigned items in a sparse array, allowing you to determine the sort order just by using the original index-part of the key.
If you don't have access to forEach, you can accomplish a similar task by including the key in the array items. Instead of an intermediate array like this:
{Friend: [undefined, "Bob", undefined, undefined, undefined, undefined, "Fred"]}
You have one like this:
{Friend: [[6, 'Fred'],[1, 'Bob']]}
Then you sort the array and visit each item in a foreach loop, extracting the second item.
Here is code:
function rekey(obj) {
var rekey = /^(.*?)(\d+)$/;
var nestedobj = {}, newobj = {};
var key, basekeyrv, newkey, oldidx, newidx;
function basekey(key) {
return rekey.exec(key).splice(1);
}
for (key in obj) {
if (obj.hasOwnProperty(key)) {
basekeyrv = basekey(key);
newkey = basekeyrv[0];
oldidx = parseInt(basekeyrv[1], 10);
if (!nestedobj[newkey]) {
nestedobj[newkey] = [];
}
nestedobj[newkey][oldidx] = obj[key];
}
}
for (key in nestedobj) {
if (nestedobj.hasOwnProperty(key)) {
newidx = 0;
nestedobj[key].forEach(function(item){
newobj[key+newidx++] = item;
});
}
}
return newobj;
}
rekey({
"Friend1" : "Bob",
"Friend6" : "Fred",
"Friend632" : "Gonzo",
"FriendFinder1" : "Dolly",
"FriendFinder4294" : "Jan"
});
produces
{Friend0: "Bob",
Friend1: "Fred",
Friend2: "Gonzo",
FriendFinder0: "Dolly",
FriendFinder1: "Jan"}
Alternatively, without using forEach:
function rekey(obj) {
var rekey = /^(.*?)(\d+)$/;
var nestedobj = {}, newobj = {};
var key, basekeyrv, newkey, oldidx, newidx;
function basekey(key) {
return rekey.exec(key).splice(1);
}
for (key in obj) {
if (obj.hasOwnProperty(key)) {
basekeyrv = basekey(key);
newkey = basekeyrv[0];
oldidx = parseInt(basekeyrv[1], 10);
if (!nestedobj[newkey]) {
nestedobj[newkey] = [];
}
nestedobj[newkey].push([oldidx, obj[key]]);
}
}
for (key in nestedobj) {
if (nestedobj.hasOwnProperty(key)) {
nestedobj[key].sort();
for (newidx = 0; newidx < nestedobj[key].length; newidx++) {
newobj[key+newidx] = nestedobj[key][newidx][1];
}
}
}
return newobj;
}
Could you try doing the following:
{
friend: new Array(),
friendFinder: new Array()
}
then you can:
friend.push() - Add to array
var index = friend.indexOf("Bob") - find in array
friend.splice(index, 1) - remove from the array at index the 1 is for the number to remove.

how check and substitute values in an array?

I have an array done with values from some radio buttons, say myArray = ["1","40","35"];
every value has his counterparts, say for instance 1 = "men", 2 = "women", 40 = "red hairs".
what's the best method to build another array where every values gets his counterpart?
so something like that myBrandNewArray = ["men","red hairs", …];
I should store my couples into variables for some maintenance, like
var "1" = "men", "2" = "women", … ;
but I don't know if this is a good approach…
ps. even pointing me to some resources will be great. Thank you.
I would keep a Hash of values
hash = { '1': 'Men', '2': 'Women' ... }
Then [ '1', '2', ... ].map( function(v) { return hash[v]; } );
IE9- will not accpet this, in this case you could just iterate in a for loop
Why don't you use an object as associative array?
var array = new Object();
array["1"] = "men"
array["40"] = "red hairs"
You can create an object like:
var arr = {
'1' : 'men',
'2' : 'women'
}
You can always access this easily like : arr['1'] == 'men'
if you want to create from existing arrays:
say myArray & myBrandNewArray
you can do something like
var arr = {};
foreach ( var i in myArray ) {
arr[myArray[i]] = myBrandNewArray[i];
}
i think this function
myArray = ["1","40","35"];
myBrandNewArray = myArray.map(function(element){ /* your code to get the right array 8/ })
source: http://www.tutorialspoint.com/javascript/array_map.htm
there is also a jQuery (cross browser) version of this function, for more details about that look here jQuery.map(myArray, function(value, index){ /*....*/ })
Use an object:
var val = {
1: "men",
40: "red hairs"
};
alert(val[1]);
alert(val[2])
;
well, finally I did this:
having
var numericalArray = ["1","50","45", …];
and
var couples = { "50" : "homme",
"1" : "femme",
"85" : "court",
…
};
I can call this and get a new array with coupled values:
function assignValues(numericalArray) {
var verbalArray = [];
for (var i=0; i<numericalArray.length; i++) {
var value = numericalArray[i];
verbalArray.push(couples[value]); // right, I can't check if the values exists
}
console.log('here my new array:', verbalArray);
}
thanks to have me pointed on use of an object.

Categories

Resources