0

i have two json which i want to merge them in a way that all new object of 2nd json will add to existing object of 1st json but just new not those item is is already exist.

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

result:

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

expected result:

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

i am doing it with using lodash but the result is not what i want.

do you have any idea how to do it. thanks

Jan
  • 125
  • 1
  • 9

1 Answers1

0

You can use Set

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]))
ellipsis
  • 12,049
  • 2
  • 17
  • 33