【发布时间】:2021-10-16 00:32:56
【问题描述】:
const _ = require('lodash');
const parentDetails = [
{
'name': '5003',
'id': '1'
},
{
'name': '5000',
'id': '2'
}
];
const childrenDetails = [
{
'cid': '11',
'Reference': '5003'
},
{
'cid': '22',
'Reference': '5000'
}
];
使用lodash 库的所需输出:从第二个数组中提取匹配的reference 与第一个数组的name,并将匹配的子详细信息作为对象附加到第一个数组,如下所示。结果不应改变原始数组。
result = [
{
'name': '5003',
'id': '1',
'childrenDetail' : {
'cid': '11',
'Reference': '5003'
}
},
{
'name': '5000',
'id': '2',
'childrenDetail' : {
'cid': '22',
'Reference': '5000'
}
}
];
【问题讨论】:
-
我认为您不需要
lodash,到目前为止您尝试过什么? -
result = []; for (const i of parentDetails ) { for (const j of childrenDetails ) { if (i.name === j.reference) { i.childrenDetail = j; result.push(i); } } } -
我想要使用 lodash 库获得相同的输出。这是任务的一部分。
标签: javascript arrays lodash