将多个Javascript对象合并为一个对象

时间:2018-07-03 16:14:41

标签: javascript jquery object orgchart

我正在尝试将javascript对象全部添加到一个变量中,但不在同一对象中。这是我的意思:

object1 = {id: 1, name: Dean};
object2 = {id: 2, name: Sam};
object3 = {id: 3, name: Castiel};

我需要他们成为:

object1 = {id: 1, name: Dean}, {id: 2, name: Sam}, {id: 3, name: Castiel};

我目前正在从ajax调用中检索所有这些信息,并且需要遍历它,并将其返回到有效的javascript对象中,并将所有这些对象立即传递给变量:

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

主要目标:dataSource属性的最终值应如下所示:

var orgchart = new getOrgChart(document.getElementById("cast"), {
    dataSource: [{id: 1, name: Dean}, {id: 2, name: Sam}, {id: 3, name: Castiel}]
});

编辑:解决方案,根据提供的答案,我修改了代码,现在它可以正常运行,我误解了控制台日志输出的内容和允许的语法。

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

3 个答案:

答案 0 :(得分:3)

我想指出的是,下面的代码无效。

object1 = {id: 1, name: Dean}, {id: 2, name: Sam}, {id: 3, name: Castiel};

您应该使用一个数组来保存这些值,如下所示:

const objects = [{id: 1, name: Dean}, {id: 2, name: Sam}, {id: 3, name: Castiel}];

注意:您将能够使用push()将新对象添加到数组中。

答案 1 :(得分:0)

自从我喜欢表演

var parent = { objectOne: { id: 1, name: 'Dean' },  objectTwo: { id: 2, name: 'Sam' },  object3: { id: 3, name: 'Castiel' } }

或作为数组

var parent = [{ id: 1, name: 'Dean' }, { id: 2, name: 'Sam' }, { id: 3, name: 'Castiel' } ]

希望这会有所帮助

答案 2 :(得分:0)

您当前的我需要它们是:要求对于Javascript 无效

is

您可以尝试通过这种方式

object1 = {id: 1, name: Dean}, {id: 2, name: Sam}, {id: 3, name: Castiel};