Search code examples
javascriptjqueryobjectorgchart

Concatenating Multiple Javascript Objects Into One Object


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);

Solution

  • 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().