How to use ES6 Spread Operator In Javascript
The spread Operator creates a new object instead of modifying it, helps us achieve immutablity which is benificial when we want to preserve original object. The ES6 spread operator (…) offers a concise and simple syntax for merging objects or object properties.
Syntax:
const mergedObject = { ...parentObject, ...childObject };
Example: This example illustrates how to merge child object values into parent keys using the ES6 spread operator.
const parentObject = {
name: "John",
age: 30,
};
const childObject = {
age: 25,
city: "New York",
};
const mergedObject = { ...parentObject, ...childObject };
console.log(mergedObject);
Output
{ name: 'John', age: 25, city: 'New York' }
How to Merge Child Object Value to Parent Key Based on Key Name in JavaScript ?
JavaScript allows us to merge values from child objects into their parent object based on a specific key name. This can be useful for organizing data or simplifying complex structures. There are several approaches available in JavaScript to merge child object values to parent key based on the key name which are as follows.
Table of Content
- Using for…in loop
- Using Object Methods
- Using ES6 Spread Operator
- Using Object.assign() Method