Reputation: 481
I am trying to add javascript objects all into one variable, but not within the same object. Here is what I mean:
object1 = {id: 1, name: Dean};
object2 = {id: 2, name: Sam};
object3 = {id: 3, name: Castiel};
I need them to be:
object1 = {id: 1, name: Dean}, {id: 2, name: Sam}, {id: 3, name: Castiel};
I am currently retrieving all this information back from an ajax call and need to loop through it and return it in a valid javascript object and pass all these objects at once to a variable:
var hierarchy;
for (i = 0; i < response['tree']['id'].length; i++) {
hierarchy = $.extend(true, hierarchy, {
id: response['tree']['id'][i],
parentId: response['tree']['parentId'][i],
Name: response['tree']['name'][i]
});
}
var orgchart = new getOrgChart(document.getElementById("cast"), {
dataSource: [hierarchy]
});
Primary objective: The dataSource property needs to end up with values that look like so:
var orgchart = new getOrgChart(document.getElementById("cast"), {
dataSource: [{id: 1, name: Dean}, {id: 2, name: Sam}, {id: 3, name: Castiel}]
});
EDIT: SOLUTION, Based on answers provided, I modified the code and now it works correctly, I misunderstood what the console log was outputting vs what syntax was allowable.
var hierarchy = [];
for (i = 1;i < response['tree']['id'].length; i++) {
groupData = {
id: response['tree']['id'][i],
parentId: response['tree']['parentId'][i],
Name: response['tree']['name'][i]
};
hierarchy.push(groupData);
}
var orgchart = new getOrgChart(document.getElementById("cast"), {
dataSource: [{
id: response['tree']['id'][0],
parentId: response['tree']['parentId'][0],
Name: response['tree']['name'][0]
}]
});
orgchart.loadFromJSON(hierarchy);
Upvotes: 0
Views: 101
Reputation: 38542
Your current I need them to be: requirement is not valid with Javascript.
object1 = {id: 1, name: Dean}, {id: 2, name: Sam}, {id: 3, name: Castiel};
You've can try with this way,
var obj = {
object1: {
id: 1,
name: 'Dean'
},
object2: {
id: 2,
name: 'Sam'
},
object3: {
id: 3,
name: 'Castiel'
}
};
var allObj = [];
// Populate allObj array
for (var key in obj) {
allObj.push(obj[key]);
}
console.log(allObj);
Upvotes: 0
Reputation: 497
Since I like the show
var parent = { objectOne: { id: 1, name: 'Dean' }, objectTwo: { id: 2, name: 'Sam' }, object3: { id: 3, name: 'Castiel' } }
Or as an array
var parent = [{ id: 1, name: 'Dean' }, { id: 2, name: 'Sam' }, { id: 3, name: 'Castiel' } ]
Hope this helps
Upvotes: 0
Reputation: 10872
I want to point out that the code below is invalid.
object1 = {id: 1, name: Dean}, {id: 2, name: Sam}, {id: 3, name: Castiel};
You should use an array to hold those values, that will look like this:
const objects = [{id: 1, name: Dean}, {id: 2, name: Sam}, {id: 3, name: Castiel}];
Note: You will be able to add new objects into the array using push()
.
Upvotes: 3