To merge two objects in JavaScript while letting the second object overwrite the same keys in the first object, you can use the Object.assign()
method.
Here's an example:
const obj1 = {a: 1, b: 2, c: 3};
const obj2 = {b: 4, c: 5, d: 6};
const mergedObj = Object.assign({}, obj1, obj2);
console.log(mergedObj);
// Output: {a: 1, b: 4, c: 5, d: 6}
In the above example, we first declare two objects obj1
and obj2
. Then we use the Object.assign()
method to merge these two objects into a new object mergedObj
. The first argument passed to the Object.assign()
method is an empty object {}
, which serves as the target object for the merge. The second argument is obj1
, and the third argument is obj2
.
Since obj2
overwrites the values of the b
and c
keys in obj1
, the resulting mergedObj
has the values of these keys as 4
and 5
respectively.
If you want to merge two objects in JavaScript while keeping the values of the duplicate keys as an array, you can use the following approach:
const obj1 = { a: 1, b: 2, c: 3 };
const obj2 = { b: 4, c: 5, d: 6 };
const mergedObj = { ...obj1 };
for (const [key, value] of Object.entries(obj2)) {
if (key in mergedObj) {
mergedObj[key] = Array.isArray(mergedObj[key]) ? mergedObj[key].concat(value) : [mergedObj[key], value];
} else {
mergedObj[key] = value;
}
}
console.log(mergedObj);
// Output: { a: 1, b: [2, 4], c: [3, 5], d: 6 }
In this example, we first declare two objects obj1
and obj2
. We create a new object mergedObj
by copying obj1
using the spread operator (...
). We then iterate over the keys and values of obj2
using Object.entries()
and check whether each key already exists in mergedObj
.
If a key exists in mergedObj
, we check whether its value is already an array using Array.isArray()
. If it is, we concatenate the new value to the existing array using Array.concat()
. If it's not, we create a new array containing the existing and new values.
If a key doesn't exist in mergedObj
, we simply add the key-value pair to mergedObj
.
Finally, we log mergedObj
to the console, which should have the values of the duplicate keys stored in arrays.