根据键将值从一个JSON数组合并到另一个数组的对应JSON中 [英] Merge value from one array of JSON into corresponding JSON of another array based on key

查看:53
本文介绍了根据键将值从一个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)

这篇关于根据键将值从一个JSON数组合并到另一个数组的对应JSON中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆