Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Combine objects and delete a property with JavaScript
We have the following array of objects that contains two objects and we are required to combine both objects into one and get rid of the chk property altogether:
const err = [
{
"chk" : true,
"name": "test"
},
{
"chk" : true,
"post": "test"
}
];
Method 1: Using Object.assign() and delete
Step 1 ? Combining objects to form a single object
const errObj = Object.assign(...err);
Step 2 ? Removing the chk property
delete errObj['chk']; console.log(errObj);
Complete Example
const err = [
{
"chk" : true,
"name": "test"
},
{
"chk" : true,
"post": "test"
}
];
const errObj = Object.assign(...err);
delete errObj['chk'];
console.log(errObj);
{ name: 'test', post: 'test' }
Method 2: Using Spread Operator and Destructuring
A more modern approach using ES6 destructuring to exclude the property during combination:
const err = [
{
"chk" : true,
"name": "test"
},
{
"chk" : true,
"post": "test"
}
];
// Combine objects and destructure to exclude 'chk'
const combined = Object.assign(...err);
const { chk, ...result } = combined;
console.log(result);
{ name: 'test', post: 'test' }
How It Works
Object.assign(...err) uses the spread operator to pass each object as a separate argument to Object.assign(). Properties from later objects overwrite properties from earlier ones with the same key. The destructuring assignment { chk, ...result } extracts the chk property and collects remaining properties into result.
Comparison
| Method | Mutates Original | ES6 Syntax | Readability |
|---|---|---|---|
| Object.assign + delete | Yes | Partial | Good |
| Destructuring | No | Yes | Better |
Conclusion
Both methods effectively combine objects and remove unwanted properties. The destructuring approach is more functional and doesn't mutate the original combined object.
