简体   繁体   English

使用Javascript合并2组Object + Array

[英]Merge 2 sets of Object + Array Using Javascript

I am trying to merge 2 sets of Object & Array like below 我试图合并两组对象和数组,如下所示

{
  exclude: ['placeholder'],
  attributes: { MYID : '' }
  map: 'input'
}

AND

{
 exclude: ['options'],
 attributes: { class: '', id:'', name:'', },
 map: '',
}

I tried using jQuery's $.extend function it worked but it only merge objects. 我尝试使用它运行的jQuery的$.extend函数,但它只合并对象。 And also tried with lodash js which also dose not work. 并尝试使用lodash js,这也不起作用。 I get output as 我输出为

{
  exclude: ['options'],
  attributes: { class: '', id: '', name: '', MYID: '' },
  map: '',
}

I need output like 我需要输出像

{
  exclude: ['options','placeholder'],
  attributes: { class: '', id: '', name: '', MYID: '' },
  map: '',
}

Code I tried using 代码我试过用

$.extend(true,{
  exclude: ['placeholder'],
  attributes: { MYID : '' }
  map: 'input'
},{
 exclude: ['options'],
 attributes: { class: '', id:'', name:'', },
 map: '',
});

You can create custom function for this using for...in loop and check type of each value. 您可以使用for...in循环创建自定义函数,并检查每个值的类型。

 var obj1 = { exclude: ['placeholder'], attributes: { MYID : '' }, map: 'input' } var obj2 = { exclude: ['options'], attributes: { class: '', id:'', name:'', }, map: '', } function merge(o1, o2) { for (var i in o2) { if (o1[i]) { if (typeof o2[i] == 'object') { if (Array.isArray(o2[i])) o1[i].push(...o2[i]) else o1[i] = Object.assign({}, o1[i], o2[i]) } else { o1[i] = o2[i] } } else { o1[i] = o2[i] } } return o1; } console.log(merge(obj1, obj2)) 

Because _.extend(...) overrides existing fields instead of fill it. 因为_.extend(...)会覆盖现有字段而不是填充它。

Try using _.mergeWith(,, customizer) with customizer function, that is responsible for merging fields the way is needed, like: 尝试使用带有自定义函数的_.mergeWith(,, customizer) ,它负责以所需方式合并字段,例如:

function customizer(initialObject, source) {
    if (_.isArray(initialObject)) {
        return initialObject.concat(source);
    } else if (_.isObject(initialObject)) {
        return _.extend(initialObject, source);
    } else {
        return source;
    }
}

_.mergeWith({a: [1], b: {c: 4}}, {a: [2, 3], b: {d: 5}}, customizer);

//{a: Array(3), b: {…}}
//a
//:
//(3) [1, 2, 3]
//b
//:
//{c: 4, d: 5}
//__proto__
//:
//Object

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

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