Introduction
In this lab, we will be exploring the process of merging objects in JavaScript. The lab will walk you through the steps of creating a new object by combining two or more objects. You will learn how to use Array.prototype.reduce() and Object.keys() to iterate over objects and keys, and Object.prototype.hasOwnProperty() and Array.prototype.concat() to merge values for existing keys.
Object Merge Function
To merge two or more objects, follow the given steps:
- Open the Terminal/SSH and type
nodeto start coding. - Use
Array.prototype.reduce()along withObject.keys()to iterate over all objects and keys. - Use
Object.prototype.hasOwnProperty()andArray.prototype.concat()to append values for keys existing in multiple objects. - Use the given code snippet to create a new object from the combination of two or more objects.
const merge = (...objs) =>
[...objs].reduce(
(acc, obj) =>
Object.keys(obj).reduce((a, k) => {
acc[k] = acc.hasOwnProperty(k)
? [].concat(acc[k]).concat(obj[k])
: obj[k];
return acc;
}, {}),
{}
);
For example, consider the following objects:
const object = {
a: [{ x: 2 }, { y: 4 }],
b: 1
};
const other = {
a: { z: 3 },
b: [2, 3],
c: "foo"
};
When you merge these two objects using the merge() function, you get the following result:
merge(object, other);
// { a: [ { x: 2 }, { y: 4 }, { z: 3 } ], b: [ 1, 2, 3 ], c: 'foo' }
Summary
Congratulations! You have completed the Merge Objects lab. You can practice more labs in LabEx to improve your skills.