【问题标题】:How to Merge two json with the different object but not merge the existing objects [duplicate]如何将两个json与不同的对象合并但不合并现有对象[重复]
【发布时间】:2019-01-28 09:28:11
【问题描述】:

我有两个 json,我想以这样的方式合并它们,第二个 json 的所有新对象都将添加到第一个 json 的现有对象中,但只是新的,而不是那些项目已经存在。

function customizer(objValue, srcValue) {
    if (_.isArray(objValue)) {
        return objValue.concat(srcValue);
    }
}
var json1 = {
    'a': [
        {'b': 2}
    ]
};

var json2 = {
    'a': [
        {'b': 2},
        {'h': 25}
    ]
};
console.log(_.mergeWith(json1, json2, customizer));

结果:

{
    a: [{b: 2}, {b: 2}, {h: 25}]
}

预期结果:

{
    a: [{b: 2}, {h: 25}]
}

我正在使用 lodash,但结果不是我想要的。

你知道怎么做吗?谢谢

【问题讨论】:

    标签: javascript arrays json object lodash


    【解决方案1】:

    你可以使用设置

    function customizer(objValue, srcValue) {
        if (_.isArray(objValue)) {
            return objValue.concat(srcValue);
        }
    }
    var json1 = {
        'a': [
            {'b': 2}
        ]
    };
    
    var json2 = {
        'a': [
            {'b': 2},
            {'h': 25}
        ]
    };
    var a=_.mergeWith(json1, json2, customizer);
    console.log(new Set([...a]))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-14
      • 2016-03-16
      • 2017-09-22
      • 2019-08-27
      相关资源
      最近更新 更多