I am trying to write a function that merges two objects by their key. The objects both have an array of numbers as their value pair and it is the arrays I want to merge.
The input for this function is
const obj1 = {
foo: [1, 2],
bar: [3],
baz: [4],
};
const obj2 = {
foo: [5],
baz: [6, 7],
};
The output should be
{
foo: [1, 2, 5],
bar: [3],
baz: [4, 6, 7]
}
I tried using concat and spread operator however the answer I get is missing the "5" from the second object's foo. Also, I noticed with my current approach, if a key/value pair exists only in obj2, it will not be copied. Is there a better approach to this problem? Here's my code, please help!
function mergeByKey(obj1, obj2) {
let resultObj = {};
for (let key1 in obj1) {
for (let key2 in obj2) {
if (key1 === key2) {
resultObj[key1] = [...obj1[key1], ...obj2[key1]];
} else {
resultObj[key1] = obj1[key1];
}
}
}
return resultObj;
}
**Output from code**
{ foo: [ 1, 2 ], bar: [ 3 ], baz: [ 4, 6, 7 ] }