gpt4 book ai didi

javascript - 在 lodash 中合并两个对象

转载 作者:行者123 更新时间:2023-11-29 10:41:00 26 4
gpt4 key购买 nike

我有两个对象数组如下:

$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
}];

在这里我想替换最后一个,其中 ma​​pped_field 与 var1 的 ma​​pped_field 匹配并且 var1 的剩余部分也合并到最后一个。

最终应该是这样的:

$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
}];

任何帮助将不胜感激。

最佳答案

使用 lodash 函数的组合:_.forEach_.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);
}
});

链接到 jsbin

关于javascript - 在 lodash 中合并两个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29352160/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com