简体   繁体   中英

merge two objects in lodash

I have two arrays of objects as follows:

$scope.var1 = [{
    "field_name": "fname",
    "mapped_field": "firstName",
    "position": 2
}, {
    "field_name": "lname",
    "mapped_field": "lastName",
    "position": 1
}, {
    "field_name": "email",
    "mapped_field": "Email",
    "position": 1
}];

$scope.final = [{
    "field_name": "fname",
    "mapped_field": "lastName",
    "position": 2
}, {
    "field_name": "lname",
    "mapped_field": "firstName",
    "position": 1
}];

Here I want to replace final one where mapped_field matched with var1's mapped_field and remaining of var1 also merged into final one.

Final should be like this:

$scope.final = [{
    "field_name": "fname",
        "mapped_field": "firstName",
        "position": 2
}, {
    "field_name": "lname",
    "mapped_field": "lastName",
    "position": 1
}, {
    "field_name": "email",
    "mapped_field": "Email",
    "position": 1
}];

Any help will highly be appreciated.

Use the combination of lodash functions: _.forEach and _.assign :

_.forEach($scope.var1, function(varObject) {
    //find object with the same mapped_field
    var finalArrayItem = _.find($scope.final, {mapped_field: varObject.mapped_field});
    if (finalArrayItem) {
        //merge objects
        _.assign(finalArrayItem, varObject);
    } else {
        $scope.final.push(varObject);
    }
});

Link to jsbin

Here's what I came up with:

final = _.map(var1, function(item) {
    return _.assign(
        _.find(final, _.pick(item, 'mapped_field')) || {},
        item
    );
});

Where you're using map() to create the create the new final array. The array that's being mapped is var1 , and we return a new object for each array item. The assign() function is used to override properties in final with properties from var1 .

To map the current final item with it's var1 item, you use find() . The pick() function is handy for constructing the filter object. Here, you say that you want to match against the mapped_field property.

The logical || is necessary for the case where there's no match. For instance, the email object. This will just copy over all the var1 properties into the empty object, and return that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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