Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge and replace objects from two arrays based on a key in javascript?

I have two array object(arrayList1,arrayList2). Just I am trying to merge those two arrays into one array object. The following terms I used.

  • Both array merged into one array based on key-name is type.
  • arrayList2 values will be overwrite the arrayList1.
  • I Got the expected output but I am worying to do with efficient and performance way..

Can someone please simplify my code..

Note :

  • It would be great if using Array.reduce function and without use any plugin/library..
  • I added the smaple input for understanding. The element order will be change and size of both array's will change.

const arrayList1 = [
    { type: "A", any: 11, other: "ab", props: "1" },
    { type: "B", any: 22, other: "bc", props: "2" }, // same type
    { type: "C", any: 33, other: "df", props: "3" }
];
 
const arrayList2 = [
    { type: "D", any: 44, other: "aa", props: "11" },
    { type: "B", any: 22, other: "bb", props: "2----2" , x: 10}, // same type
    { type: "E", any: 44, other: "cc", props: "33" }
];

result = arrayList2.reduce(function (arr1, arr2) {
  let isMatchFound = false;
  arr1.forEach(function (list) {
    if (arr2.type == list.type) {
      list = Object.assign(list, arr2);
      isMatchFound = true;
    }
  });
  if (!isMatchFound) {
    arr1.push(arr2);
  }
  return arr1;
}, arrayList1);

console.log('result', JSON.stringify(result));
like image 672
RSKMR Avatar asked Oct 17 '22 07:10

RSKMR


1 Answers

You may also use .reduce() and Object.values() methods to get the desired output:

const arrayList1 = [
    { type: "A", any: 11, other: "ab", props: "1" },
    { type: "B", any: 22, other: "bc", props: "2" }, // same type
    { type: "C", any: 33, other: "df", props: "3" }
];
 
const arrayList2 = [
    { type: "D", any: 44, other: "aa", props: "11" },
    { type: "B", any: 22, other: "bb", props: "2----2" , x: 10}, // same type
    { type: "E", any: 44, other: "cc", props: "33" }
];

const result = Object.values(
   [].concat(arrayList1, arrayList2)
     .reduce((r, c) => (r[c.type] = Object.assign((r[c.type] || {}), c), r), {})
);
                 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 95
Mohammad Usman Avatar answered Nov 01 '22 11:11

Mohammad Usman