4 回答
TA贡献1880条经验 获得超4个赞
您可以e[k]
在添加之前检查是否已定义,方法是使用obj
以下命令检查e
对象是否具有该属性:k
.hasOwnProperty()
const array = [{ "value": "0", "name": "5", "waste": "remove", "city": "NY" }, { "value": "0", "name": "51", "waste": "remove", } ];
const keys_to_keep = ['name', 'city'];
const result = array.map(e => {
const obj = {};
keys_to_keep.forEach(k => {
if (e.hasOwnProperty(k))
obj[k] = e[k]
});
return obj;
});
console.log(result)
如果要删除的键不是动态的,您还可以使用解构赋值来提取要丢弃的属性,并使用其余语法来获取没有这些属性的对象:
const array = [{ "value": "0", "name": "5", "waste": "remove", "city": "NY" }, { "value": "0", "name": "51", "waste": "remove", } ];
const result = array.map(({value, waste, ...r}) => r);
console.log(result)
TA贡献1934条经验 获得超2个赞
您可以检查 forEach 中的值是否未定义:
const result = array2.map(e => {
const obj = {};
keys_to_keep.forEach(k => {
if (undefined !== e[k]) {
obj[k] = e[k]
}
)
return obj;
});
TA贡献1797条经验 获得超4个赞
您可以使用.map
迭代对象,Object.entries
获取每个项目的键值对,Object.fromEntries
将它们分组到结果对象中,并.filter
仅获取带有key
inkeys_to_keep
和 avalue
不是 的条目undefined
:
const array1 = [
{ "value": "0", "name": "5", "waste": "remove", "city": "NY" },
{ "value": "0", "name": "51", "waste": "remove" }
];
var keys_to_keep = ['name', 'city'];
const result = array1.map(item =>
Object.fromEntries(
Object.entries(item).filter(([key, value]) =>
keys_to_keep.includes(key) && value !== undefined
)
)
);
console.log(result)
TA贡献1804条经验 获得超2个赞
我将回答这两部分。以下是执行此操作的步骤。
map()
在主阵列上使用。使用 获取每个对象的条目
Object.entries()
。应用于
filter()
整个数组,删除那些键不存在的整体keys_to_keep
现在进入第二部分。
使用
keys_to_keep
创建一个对象,其中每个键包含未定义的值。再次使用
map()
上一个结果并使用 Spread 运算符。首先传播上面创建的对象,然后传播原始值。这样,如果没有找到任何键,它将被设置为undefined
const
array1 = [
{
"value": "0",
"name": "5",
"waste": "remove",
"city": "NY"
},
{
"value": "0",
"name": "51",
"waste": "remove",
}
]
var keys_to_keep = ['name', 'city']
let obj = Object.fromEntries(keys_to_keep.map(x => [x, undefined]));
const res = array1.map(obj =>
Object.fromEntries(
Object.entries(obj).filter(([k, v]) => keys_to_keep.includes(k))))
.map(x => ({...obj, ...x}))
console.log(res)
添加回答
举报