有人可以帮助我合并两个对象数组吗,请在javascript中使用loadash?下面是示例数组。我尝试过_merge
arr 1= [
{
"areaId": 1,
"areaName": "areanam222",
"businessExecutiveId": 1
},
{
"areaId": 2,
"areaName": "arename",
"businessExecutiveId": 1
}
]
arr2 =[
{
"id": 1,
"name": "BN",
}
]
arrResult =[
{
"areaId": 1,
"areaName": "areanam222",
"businessExecutiveId": 1,
"id": 1,
"name": "BN"
}, {
"areaId": 2,
"areaName": "arename",
"businessExecutiveId": 1,
"id": 1,
"name": "BN"
}
]
我尝试了以下选项,但它只返回一条记录。
var arrResult = _(list).keyBy('businessExecutiveId').merge(_.keyBy(this.typeaheadDataList, 'id')).values() .value();
我也在下面尝试过 const c = _.assign([],arr1,arr2);
我得到的荡妇如下
{ 编号:1 名称:“ BN” }, { areaId:1 areaName:“ ASas”, businessExecutiveId:1 编号:1 名称:“ BN” }
请帮助我
答案 0 :(得分:0)
您不需要lodash就能做到这一点。为什么不使用javascripts reduce
函数将arr2对象中的所有对象键合并到数组1的对象中,就像这样
arr1.reduce((arr, obj) => {
const newObj = arr2.reduce((o, insideObj) => ({
...o,
...insideObj
}), obj)
return [...arr, newObj]
}, [])
答案 1 :(得分:0)
如果我们有array comprehension,我们可能会使用以下内容:
[
for (a of arr1)
for (b of arr2)
if(a.businessExecutiveId === b.id) {...a, ...b}
]
在没有数组理解的情况下,我们使用flatMap:
_(arr1).flatMap(a =>
_(arr2).flatMap(b =>
a.businessExecutiveId === b.id ? [{...a, ...b}] : []
).value()
).value()
var arr1= [
{
"areaId": 1,
"areaName": "areanam222",
"businessExecutiveId": 1
},
{
"areaId": 2,
"areaName": "arename",
"businessExecutiveId": 1
},
{
"areaId": 3,
"areaName": "bname",
"businessExecutiveId": 2
}
]
var arr2= [
{
"id": 1,
"name": "BN",
},
{
"id": 2,
"name": "CM",
}
]
res = _(arr1).flatMap(a =>
_(arr2).flatMap(b =>
a.businessExecutiveId === b.id ? [{...a, ...b}] : []
).value()
).value()
console.log(res)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
答案 2 :(得分:0)
arr1.reduce((arr, obj) => {
const newObj = arr2.reduce((o, insideObj) => ({
...o,
...insideObj
}), obj)
return [...arr, newObj]
}, [])
我使用以下代码解决了该问题。
_.map(list, function(item) {
return _.merge(item, _.find(temp, function(o) {return o.id == item.businessExecutiveId }) );
});