如何在数组中添加一些没有指定 属性 的对象的新 属性? (JS)

How to add new property of some objects in the array that doesn't have the specified property? (JS)

我正在尝试向数组中没有 属性 的对象添加新的 属性。

const updatedArray = items.filter(item => !item.hasBox)...

在为所有那些数组中没有 hasBox 的对象添加具有静态值的新 has 框 属性 过滤之后剩下的部分应该是什么?

您可以将包含 hasBox 的每个元素映射到自身,并将具有默认值的 hasBox 添加到所有其他元素。原始数组没有改变。你应该使用 hasOwnProperty 而不是 !item.hasBox 来检查一个对象是否有 属性 否则你会得到错误的值如 '', 0, null, undefined, ...

const items = [
    {},
    {hasBox: undefined},
    {hasBox: true},
    {hasBox: false},
    {hasBox: null},
    {hasBox: ''},
    {hasBox: 0}
];
const updatedArray = items.map(item => 
    !item.hasOwnProperty('hasBox') ? {...item, hasBox: 'default'} : item);
console.log(items);
console.log(updatedArray);