简体   繁体   English

如何在JavaScript中合并两个具有不同结构的对象?

[英]How can I concat two objects with different structure in Javascript?

I have two objects that look like this: 我有两个看起来像这样的对象:

var a = [{
    id: 0,
    name: "Zero"
}];
var b = [{
    id: 1,
    name: "one",
    firstName: "First"
}],
    [{
        id: 2,
        name: "two",
        firstName: "Second"
    }], [{
        id: 3,
        name: "three",
        firstName: "Third"
    }];

I want to concat the two objects in Javascript to look something like this: 我想在Javascript中合并两个对象,使其看起来像这样:

var c = [{
    id: 0,
    name: "Zero"
}],
    [{
        id: 1,
        name: "one",
        firstName: "First"
    }], [{
        id: 2,
        name: "two",
        firstName: "Second"
    }], [{
        id: 3,
        name: "three",
        firstName: "Third"
    }];

Is there an easy way to do this? 是否有捷径可寻?

Although what you've posted doesn't look valid, your objects are in arrays so you can use .concat 尽管您发布的内容看起来无效,但是您的对象位于数组中,因此您可以使用.concat

var a = [{id: 0, name: "Zero"}];
var b = [
    [{id: 1, name: "one", firstName:"First"}], 
    [{id: 2, name: "two", firstName:"Second"}], 
    [{id: 3, name: "three", firstName: "Third"}]
];

var c = a.concat(b);

if there is no reason why your objects are in individual arrays, you'd want b to be: 如果没有理由将对象放在单独的数组中,则希望b为:

var b = [
    {id: 1, name: "one", firstName:"First"}, 
    {id: 2, name: "two", firstName:"Second"}, 
    {id: 3, name: "three", firstName: "Third"}
];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM