首页 > 解决方案 > 合并对象并删除属性

问题描述

假设我有一个像这样结构的对象数组

"err": [
    {
        "chk" : true,
        "name": "test"
    },
    {
        "chk" :true
        "post": "test"
    }
]

我怎样才能像这样重新构造它:

"err": [
    {
        "post": "test"
        "name": "test"
    }
]

我试过了

arr.filter(obj => delete obj.chk);

它可以成功删除chk属性,但是如何将两个对象结合起来呢?

标签: javascriptarrays

解决方案


您可以将它们传播Object.assign到创建一个新对象,然后chk从该对象中删除该属性:

const err = [
    {
        "chk" : true,
        "name": "test"
    },
    {
        "chk" :true,
        "post": "test"
    }
];
const newObj = Object.assign({}, ...err);
delete newObj.chk;
console.log([newObj]);

另一种不删除的方法是chk在左侧进行解构,并使用 rest 语法:

const err = [
    {
        "chk" : true,
        "name": "test"
    },
    {
        "chk" :true,
        "post": "test"
    }
];
const { chk: _, ...newObj } = Object.assign({}, ...err);
console.log([newObj]);


推荐阅读