Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine object and delete a property

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?

like image 330
Beginner Avatar asked Feb 14 '20 06:02

Beginner


People also ask

How do you remove a property of an object?

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.

How do I remove a property from an array of objects?

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.

How do you combine properties of two objects?

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.


1 Answers

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]);
like image 91
CertainPerformance Avatar answered Oct 17 '22 13:10

CertainPerformance