将多个 Javascript 个对象连接成一个对象

Concatenating Multiple Javascript Objects Into One Object

我正在尝试将 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 调用中检索所有这些信息,需要遍历它并 return 它在一个有效的 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]
});

主要 objective:数据源 属性 需要以如下所示的值结束:

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

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

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

将新对象添加到数组中

因为我喜欢这个节目

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' } ]

希望对您有所帮助

您当前的 我需要它们: 要求 无效 Javascript。

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

你可以试试这个方法,

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