合并对象并删除属性



假设我有一个结构如下的对象数组

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

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

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

我试过了

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

它可以成功删除chk属性,但如何组合这两个对象?

您可以将它们分散到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]);

最新更新