Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

javascript - Merge value from one array of JSON into corresponding JSON of another array based on key

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'
}]

The final array should be:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...