Supposed I have an array of objects structured like this
"err": [
{
"chk" : true,
"name": "test"
},
{
"chk" :true
"post": "test"
}
]
How can I re-structure it like this:
"err": [
{
"post": "test"
"name": "test"
}
]
I tried
arr.filter(obj => delete obj.chk);
It can successfully delete the chk
property, but how can I combine the two objects?
The JavaScript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically.
To remove a property from all objects in an array:Use the Array. forEach() method to iterate over the array. On each iteration, use the delete operator to delete the specific property. The property will get removed from all objects in the array.
To merge objects into a new one that has all properties of the merged objects, you have two options: Use a spread operator ( ... ) Use the Object. assign() method.
You can spread them into Object.assign
to create a new object, then remove the chk
property from that object:
const err = [
{
"chk" : true,
"name": "test"
},
{
"chk" :true,
"post": "test"
}
];
const newObj = Object.assign({}, ...err);
delete newObj.chk;
console.log([newObj]);
Another method, without deleting, would be to destructure chk
on the left-hand side, and use rest syntax:
const err = [
{
"chk" : true,
"name": "test"
},
{
"chk" :true,
"post": "test"
}
];
const { chk: _, ...newObj } = Object.assign({}, ...err);
console.log([newObj]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With