[英]Removing attribute from an Object Array by key string
我有一个对象数组,我想通过调用函数并传递该数组和要删除的键来删除该对象的一些属性。
我在Stack Overflow上提到了这个答案,当我手动指定键(如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')
调用此函数this.removeKeyFromObjectsArray(this.updatedProducts, 'id')
但是此数组中的对象仍然具有键。 ( this
是因为它在Vue App中,并且我需要在同一实例中引用其他函数)。
如果我们手动指定键名称(例如id
,则此函数有效,但是当我们通过参数传递键字符串然后使用它时,该功能不起作用,有人可以在这里解释什么问题,我该如何解决?
要在解构中使用计算的属性名称 ,您需要用[]
包装key
,并将其分配给新变量(在本例中为_
)。 否则,它将从对象中解构名为"key"
的属性,而不是具有key
变量中值的属性
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') )
那就是删除文字key
-使用带有方括号[]
动态属性符号来获得所需的结果:
const newArray = products.map(({ [key]: _, ...otherAttributes }) => otherAttributes);
我为上面的_
分配不需要的密钥的原因是因为习惯_
用作“不需要的”或“忽略此”密钥。 请注意,这是加前缀与键不同_
( _key
),这意味着“不直接修改此-使用的getter或setter方法,而不是”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.