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 bine the two objects?
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 bine the two objects?
chk
?
– trincot
Commented
Feb 14, 2020 at 6:29
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]);
More declarative way (not imperative):
const bine = (...objs) => objs.reduce((merged, obj) => ({ ...merged, ...obj }), {});
// can be more functional - you can try to improve it
const deleteProps = (obj, ...props) => {
props.forEach((prop) => {
delete obj[prop];
});
return obj;
}
// Example usage:
const merged = bine(...[{ a: 'A', err: 'X' }, { b: 'B' }], { c: 'C' }, { d: 'D' }, { e: 'E' });
const result = deleteProps(merged, 'e', 'err', 'error');
console.log(result);