Search code examples
javascriptarrays

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?


Solution

  • 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]);