根据键将值从一个JSON数组合并到另一个数组的对应JSON中
我有两个JSON对象数组.一个带有承包商的详细信息,另一个带有项目.两者都有一个共同的字段user_id.
I have two arrays of JSON objects. One with contractor details and another with projects. Both have a common field user_id.
我想要对象的结果数组,以便每个承包商也有一个其活动项目的数组.示例:
I want a resultant array of objects such that each contractor also has an array of his active projects. Example:
arr1 = [{
name: 'Contractor A',
user_id: 3,
mobile_number: '9999999999',
active_projects: []
},
{
name: 'Contractor B',
user_id: 6,
mobile_number: '9999999999',
active_projects: []
}]
arr2 = [{
user_id: 3, project_name: 'Project A'
},
{
user_id: 3, project_name: 'Project B'
},
{
user_id: 6, project_name: 'Project C'
}]
最终数组应为:
arr1 = [{
name: 'Contractor A',
user_id: 3,
mobile_number: '9999999999',
active_projects: ['Project A', 'Project B']
},
{
name: 'Contractor B',
user_id: 6,
mobile_number: '9999999999',
active_projects: ['Project C']
}]
实现此目标的最佳/最干净的方法是什么?
What is the best/cleanest way to achieve this?
您可以使用 forEach
&迭代 arr2
.在回调内部,使用 findIndex
从 arr1
查找对象的索引,该对象的 user_id
与下面的对象的 user_id
相匹配迭代.然后使用 index
填充第一个数组中的值
You can iterate arr2
using forEach
& inside callback use findIndex
to find the index of object from arr1
whose user_id
matches with the user_id
of the object under iteration. Then use the index
to populate the value in the first array
let arr1 = [{
name: 'Contractor A',
user_id: 3,
mobile_number: '9999999999',
active_projects: []
},
{
name: 'Contractor B',
user_id: 6,
mobile_number: '9999999999',
active_projects: []
}
]
let arr2 = [{
user_id: 3,
project_name: 'Project A'
},
{
user_id: 3,
project_name: 'Project B'
},
{
user_id: 6,
project_name: 'Project C'
}
];
arr2.forEach((item) => {
const findIndexArr1 = arr1.findIndex(elem => elem.user_id === item.user_id);
if (findIndexArr1 !== -1) {
arr1[findIndexArr1].active_projects.push(item.project_name)
}
});
console.log(arr1)