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

问题描述

我正在尝试向数组中没有该属性的对象添加一个属性

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

将具有静态值的新 has Box 属性添加到数组中没有 hasBox 的所有对象的过滤后,剩下的部分应该是什么?

解决方法

您可以将包含 hasBox 的每个元素映射到自身,并将具有默认值的 hasBox 添加到所有其他元素。原始数组没有改变。您应该使用 hasOwnProperty 而不是 !item.hasBox 来检查对象是否具有属性,否则对于 ''0null 等值,您会得到错误的结果,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);