Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

How to merge array of objects by key in JavaScript

2 Answers

0 votes
function mergeArrayOfObjects(arr1,arr2) {
  return arr1.map((item, i)=>{
     if (item.id === arr2[i].id) {
       return Object.assign({},item,arr2[i])
     }
  })
}


const arr1 = [
  {id:1, lang:"javascript"},
  {id:2, lang:"c++"},
  {id:3, lang:"c"}
];
const arr2 = [
    {id:1, password:3452},
    {id:2, password:9838},
    {id:3, password:1273}
];

console.log(mergeArrayOfObjects(arr1, arr2));






/*
run:

[{
  id: 1,
  lang: "javascript",
  password: 3452
}, {
  id: 2,
  lang: "c++",
  password: 9838
}, {
  id: 3,
  lang: "c",
  password: 1273
}]

*/

 



answered May 21, 2021 by avibootz
edited May 21, 2021 by avibootz
0 votes
function mergeArrayOfObjects(arr1,arr2){
   	let i = 0;
  	let mergeArr = [];

  	while (i < arr1.length) {
      if (arr1[i].id === arr2[i].id) {
        mergeArr.push({...arr1[i], ...arr2[i]})    
      }
      i++;
    }
  return mergeArr;
}


const arr1 = [
  {id:1, lang:"javascript"},
  {id:2, lang:"c++"},
  {id:3, lang:"c"}
];
const arr2 = [
    {id:1, password:3452},
    {id:2, password:9838},
    {id:3, password:1273}
];

console.log(mergeArrayOfObjects(arr1, arr2));






/*
run:

[{
  id: 1,
  lang: "javascript",
  password: 3452
}, {
  id: 2,
  lang: "c++",
  password: 9838
}, {
  id: 3,
  lang: "c",
  password: 1273
}]

*/

 



answered May 21, 2021 by avibootz
edited May 21, 2021 by avibootz

Related questions

1 answer 121 views
1 answer 113 views
113 views asked Feb 21, 2022 by avibootz
1 answer 136 views
2 answers 155 views
2 answers 202 views
2 answers 189 views
...