I have the below scenario where I am trying to merge two arrays of objects.
The current code works, but I am looking for a more efficient way.
var constList = [
{ name: "jack", id: "1", designation: "hr" },
{ name: "mary", id: "2", designation: "it" },
{ name: "john", id: "3", designation: "fin" }
]
var apiList = [
{ name: "jack", id: "1", height: "10" },
{ name: "mary", id: "2", height: "20" }
]
var temp = [];
constList.forEach(x => {
apiList.forEach(y => {
if (x.id === y.id) {
temp.push({ ...x,
...y
});
}
});
});
console.log(temp);
-
1\$\begingroup\$ Welcome to CR! Are your array ids guaranteed to be sorted sequentially ascending and without gaps as they are in this example? \$\endgroup\$ggorlen– ggorlen2019年12月18日 16:05:52 +00:00Commented Dec 18, 2019 at 16:05
-
1\$\begingroup\$ They are consecutive but there could be gaps. \$\endgroup\$user804401– user8044012019年12月18日 16:09:41 +00:00Commented Dec 18, 2019 at 16:09
1 Answer 1
You can use reduce
for this purpose. Group the objects into an aggregate object by some key which we can make a parameter to a function mergeByKey
. This function takes any number of object arrays which are then flattened (change flat
to [].concat(...objArrs)
for better browser compatibility) then reduce
d into a single object. During grouping, object spreading updates the value for each unique key as you did. Finally, extract the array of values from the grouping object using Object.values
which is the final result.
Time complexity of the original version was O((n*longest_obj_length)^2)
, but the updated version is O(n*longest_obj_length)
.
const mergeByKey = (key, ...objArrs) =>
Object.values(objArrs.flat().reduce((a, e) => {
a[e[key]] = {...a[e[key]], ...e};
return a;
}, {}))
;
const constList = [
{ name: "jack", id: "1", designation: "hr" },
{ name: "mary", id: "2", designation: "it" },
{ name: "john", id: "3", designation: "fin" }
];
const apiList = [
{ name: "jack", id: "1", height: "10" },
{ name: "mary", id: "2", height: "20" }
];
console.log(mergeByKey("id", constList, apiList));