How to Merge Child Object Value to Parent Key Based on Key Name in JavaScript ?
Last Updated :
21 Aug, 2024
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.
Using for...in loop
In this method, the loop iterates through the properties of an object using a for...in loop, which helps you to access both the keys and their corresponding values. The loop checks whether each key from the child object exists in the parent object It selectively merges only those properties from the child object that are present in the parent object.
Syntax:
for (let key in childObject) {
if (parentObject.hasOwnProperty(key)) {
parentObject[key] = childObject[key];
}
}
Example 1: This example demonstrates how to merge child object values into parent keys using a for...in loop.
JavaScript
let parentObj = {
name: "John",
details: {
age: 30,
city: "New York",
},
};
for (let key in parentObj.details) {
parentObj[key] = parentObj.details[key];
}
delete parentObj.details;
console.log(parentObj);
Output{ name: 'John', age: 30, city: 'New York' }
Using Object Methods
This approach utilizes built-in JavaScript object methods such as Object.keys() and Array.prototype.forEach() to make the merging process in a functional style. The forEach() method iterates over the array of keys extracted from the child object, allow us for clear and readable code.
Syntax:
const keys = Object.keys(childObject);
keys.forEach(key => {
if (parentObject.hasOwnProperty(key)) {
parentObject[key] = childObject[key];
}
});
Example 2: This example showcases how to merge child object values into parent keys using Object methods.
JavaScript
let parentObj = {
name: "John",
details: {
age: 30,
city: "New York",
},
};
Object.keys(parentObj.details).forEach((key) => {
parentObj[key] = parentObj.details[key];
});
delete parentObj.details;
console.log(parentObj);
Output{ name: 'John', age: 30, city: 'New York' }
Using ES6 Spread Operator
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.
JavaScript
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' }
Using Object.assign() Method
To merge values from a child object into a parent object based on a specific key name in JavaScript, you can utilize the Object.assign() method. This method copies the values of all enumerable own properties from one or more source objects to a target object and returns the target object.
Syntax:
Object.assign(target, ...sources)
Example:
JavaScript
// Parent object
let parentObj = {
name: "Balmukund",
age: 25,
};
// Child object
let childObj = {
age: 22,
city: "Surat",
};
// Merge values from childObj into parentObj based on the key "age"
Object.assign(parentObj, { age: childObj.age });
console.log(parentObj);
Output{ name: 'Balmukund', age: 22 }
Using Object.entries() with Array.prototype.reduce()
In this approach, the Object.entries() method is used to convert the child object into an array of key-value pairs. Then, Array.prototype.reduce() is utilized to iterate over these pairs and merge the child object values into the parent object. This method offers a functional approach and is useful when you want to handle more complex merging logic.
Syntax:
const mergedObject = Object.entries(childObject).reduce((acc, [key, value]) => {
if (key in acc) {
acc[key] = value;
}
return acc;
}, parentObject);
Example: The following example demonstrates how to merge the child object values into the parent object using Object.entries() and reduce().
JavaScript
// Parent object
let parentObj = {
name: "Nikunj",
details: {
age: 22,
city: "Surat",
},
};
// Merge child object values into parent object
Object.entries(parentObj.details).forEach(([key, value]) => {
parentObj[key] = value;
});
// Remove the 'details' key
delete parentObj.details;
console.log(parentObj);
Output{ name: 'Nikunj', age: 22, city: 'Surat' }
Similar Reads
How to add Key-Value pair to a JavaScript Object?
A JavaScript object has a key-value pair, and it can be of variable length. We first need to declare an object and assign the values to that object for that there can be many methods.Below are the methods to add a key/value pair to a JavaScript object:Table of ContentUsing Dot NotationUsing Bracket
4 min read
How to remove a key-value pair from JavaScript object?
Removing a key-value pair from an object in JavaScript means deleting a specific property and its corresponding value from the object. This can be achieved using the delete operator, destructuring with the rest operator, or various utility functions to manipulate the object dynamically.How to remove
3 min read
How to Change Specific Object Value to Null in JavaScript ?
We have given an array of objects and our task is to change specific object values to null using JavaScript.Below is an example for a better understanding of the problem statement.Example:Input: { name: 'GeeksforGeeks', topic: 'JavaScript' }Output: { name: 'GeeksforGeeks', topic: null }Table of Cont
3 min read
How to Get all Property Values of a JavaScript Object without knowing the Keys?
To get all property values from a JavaScript object without knowing the keys involves accessing the object's properties and extracting their values.Below are the approaches to get all property values of a JavaScript Object:Table of ContentUsing Object.values() MethodUsing Object.keys() methodApproac
2 min read
How to filter object depending on the field's value in JavaScript ?
In this article, we are given an object and the task is to filter the object depending upon the field's value in JavaScript. There are two approaches that are discussed below. Approach 1: First create an empty object with the field's value as the key. Then one by one traverse the original object and
2 min read
How to Merge Properties of Two JavaScript Objects Dynamically?
Here are two different ways to merge properties of two objects in JavaScript.1. Using Spread OperatorThe Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 value is expected. It allows the privile
1 min read
How to Merge two Different Arrays of Objects with Unique Values in JavaScript?
Merging two arrays of objects with unique values is a common task in JavaScript. This operation involves combining the elements of two arrays while ensuring that each resulting object has a unique identifier. We will explore various approaches to merging two arrays of objects with unique values. The
4 min read
How to get the first key name of a JavaScript object ?
In JavaScript, accessing the first key name of an object involves identifying the initial property defined within that object. This concept is useful when you need to interact with or manipulate object properties in a specific order, particularly when the sequence of properties is relevant.Here we h
2 min read
How to declare object with computed property name in JavaScript ?
In this article, we learn how to declare an object with a computed property name. Before beginning this article, we have to know about the javascript objects. Computed Property Names: The ES6 computed property names feature allows us to compute an expression as a property name on an object. Javascri
2 min read
How to Deep Merge Two Objects in JavaScript ?
Typically, in JavaScript, combining two objects is a commonplace thing to do, but when it involves intricate nesting, deep merging turns out to be necessary, deep merge is the activity of taking the attributes or features from multiple objects (which have nested objects) and creating a new object wi
3 min read