javascript - Combine object and delete a property - Stack Overflow

admin2025-04-20  0

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?

Share Improve this question edited Feb 14, 2020 at 6:59 CertainPerformance 372k55 gold badges352 silver badges357 bronze badges asked Feb 14, 2020 at 6:27 BeginnerBeginner 1,7405 gold badges28 silver badges49 bronze badges 3
  • which two object? after delete(which has only single object) or before delete? – Prashant Pimpale Commented Feb 14, 2020 at 6:29
  • 2 What is the logic? What is the purpose of chk? – trincot Commented Feb 14, 2020 at 6:29
  • 1 Do you really need the final result to be an array if there's just one object in it? – Barmar Commented Feb 14, 2020 at 15:38
Add a ment  | 

2 Answers 2

Reset to default 9

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);
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745114628a285790.html

最新回复(0)