gpt4 book ai didi

javascript - 通过键字符串从对象数组中删除属性

转载 作者:搜寻专家 更新时间:2023-10-30 22:54:24 26 4
gpt4 key购买 nike

我有一个对象数组,我想删除这个对象的一些属性,方法是调用一个函数并传递数组和我想删除的键。

我提到了 this在 Stack Overflow 上回答,当我手动指定 key 时它会起作用,比如 id。它删除数组中每个对象的 id 属性。

const newArray = array.map(
({
id,
...otherAttributes
}) => otherAttributes
);

但是当我将键传递给函数,然后使用参数中的键时,它无法检测到对象中的键,因此无法删除它。函数体是这样的:

removeKeyFromObjectsArray(newArray, key) {           
const newArray = products.map(
({
key,
...otherAttributes
}) => otherAttributes
);
return newArray;

我使用 this.removeKeyFromObjectsArray(this.updatedProducts, 'id') 调用此函数,但此数组中的对象仍然具有 key 。 (this 是因为它在 Vue App 中,我需要在同一实例中引用不同的函数)。

如果我们手动指定像 id 这样的键名,这个函数就可以工作,但是当我们通过参数传递键字符串然后使用它时,它就不起作用了,有人能解释一下这里的问题是什么吗?我该如何解决?

最佳答案

使用computed property names in destrcuturing ,您需要用 [] 包装 key 并将其分配给一个新变量(在本例中为 _ )。否则,它将从对象中解构一个名为 "key" 的属性,而不是 key 变量中具有 value 的属性

function removeKeyFromObjectsArray(products, key) {
const newArray = products.map(
({
[key]: _,
...otherAttributes
}) => otherAttributes
);
return newArray;
}

console.log(
removeKeyFromObjectsArray([{ id: 1, name: 'name1'},
{ id: 2, name: 'name2'}], 'name')
)

关于javascript - 通过键字符串从对象数组中删除属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56921801/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com