Skip to content

Instantly share code, notes, and snippets.

@jasp402
Created March 29, 2018 16:34
Show Gist options
  • Save jasp402/7097a71fa26e40376d42097ef95c9804 to your computer and use it in GitHub Desktop.
Save jasp402/7097a71fa26e40376d42097ef95c9804 to your computer and use it in GitHub Desktop.
merge 2 array (arKeys & ArValues) into one object with Javascript
const arr1 = [{ a: "a", 1: 1, 2: 2 }, { a: "b", 1: 1, 2: 3 }];
const arr2 = [{ a: "a", 3: 123 }, { a: "b", 3: 4411 }];
const result = [...arr1.concat(arr2) // concat the arrays
.reduce((m, o) => m.set(o.a, Object.assign(m.get(o.a) || {}, o)), // use a map to collect similar objects
new Map()
).values()]; // get the values iterator of the map, and spread into a new array
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment