简体   繁体   English

在Javascript中合并对象中的嵌套数组

[英]Merge nested array in object in Javascript

I need to merge 2 objects with nested arrays我需要将 2 个对象与嵌套数组合并

var dest = {
  id: "865",
  arr: [{
    id: "123",
    value: "First" }]
};

var src = {
  id: "865",
  arr: [{
    id: "456",
    value: "Second" }]

};

to produce生产

merge = {
  id: "865",
  arr: [{id: "123",
         value: "First"},
        {id: "456",
         value: "Second"}]
};

I tried using _.merge(dest, src) (using Lodash) and a couple of other methods, but seems like the 2nd object is overwriting the first one because it doesn't handle the nested array the way I want.我尝试使用 _.merge(dest, src) (使用 Lodash)和其他一些方法,但似乎第二个对象覆盖了第一个对象,因为它没有按照我想要的方式处理嵌套数组。

What is the best way to do this?做这个的最好方式是什么?

Thanks,谢谢,

You can use Lodash _.mergeWith method:您可以使用 Lodash _.mergeWith方法:

var dest = {
  id: "865",
  arr: [{
    id: "123",
    value: "First"
  }]
};

var src = {
  id: "865",
  arr: [{
    id: "456",
    value: "Second"
  }]

};

var merge = _.mergeWith({}, src, dest, function(a, b) {
  if (_.isArray(a)) {
    return b.concat(a);
  }
});
console.log(merge);

It allows you to pass a customizer in order to merge the array in a "custom" way.它允许您传递自定义程序,以便以“自定义”方式合并数组。

Here's the fiddle .这是小提琴 Hope it helps.希望能帮助到你。

You can use Object.assign()您可以使用Object.assign()

 var dest = { id: "865", arr: [{ id: "123", value: "First" }] }; var src = { id: "865", arr: [{ id: "456", value: "Second" }] }; var merge = Object.assign({}, dest); merge.arr.push(Object.assign({}, src.arr[0])); src.arr[0].id = 789; // should not affect `merge.arr` console.log(merge);

Without any libraries.没有任何库。

 var dest = { id: "865", arr: [{ id: "123", value: "First" }] }; var src = { id: "865", arr: [{ id: "456", value: "Second" }] }; // 1 var resultOne = { id: dest.id, arr: src.arr.concat(dest.arr) }; // 2 var resultTwo = Object.assign({}, src, { arr: src.arr.concat(dest.arr) }); // 3 var merge = function(obj1, obj2) { return Object.keys(obj1).reduce(function(result, next) { if (Array.isArray(obj1[next]) && Array.isArray(obj2[next])) { result[next] = obj1[next].concat(obj2[next]); } else if (obj1[next] && obj2[next]) { result[next] = obj2[next]; } return result; }, {}); } console.log(merge(src, dest));

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

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