如何基于动态定义的变量解构对象 [英] How to destructure an object based on a dynamic defined variable
问题描述
我正在处理一个不可变的对象,我需要添加一个不可变的对象。
I am working with an immutable object that I need to add subtract an array of values from.
我知道可以使用ES6进行以下破坏。
I know it's possible using ES6 destructing with the following.
const {countries, remainder} = someObj // {countries:...,languages:..., ...keys};
最后,剩下的就是没有国家密钥的新对象。
This will end me up with the remainder being the new Object without the countries key.
因此,我发现可以在数组上使用reduce来从对象中删除所有值,最后使用默认参数返回新对象,即
Therefore I figured out that I could use reduce on an array to go through and remove all the values from the object, returning a new object in the end, using the default parameter, being the original object.
但是,我不确定该如何处理,因为键的名称在数组中定义。
However, I am not sure how to go about it, because the names of keys are defined in the array.
arrayToRemove.reduce((total, value) => {
const { extractValue: [value], ...remainder } = total
return remainder;
}, { ...originalObj });
arrayToRemove.reduce((total, value) => {
const { [extractValue], ...remainder } = total
return remainder;
}, { ...originalObj });
我期望最终得到一个新的Object,而没有包含在名为arrayToRemove的数组中的键。
I am expecting to end up with a new Object without the keys that are contained in the array called arrayToRemove.
我需要在保持不变性的同时执行此操作,因此我不能仅遍历原始对象并将其从其中删除,因此我认为上述方法是一个聪明的方法。
I need to do this while maintaining immutability, so I cannot just loop through the original object and remove them from it, so I thought the above would be a bright way to go about it.
感谢任何帮助。
推荐答案
您可以使用计算出的属性名称
在此处了解更多信息:对象属性分配模式[YDKJS:ES6&
Read more here: object property assignment pattern [YDKJS: ES6 & Beyond]
var originalObj = { foo: 1, bar: 2, baz: 3, },
arrayToRemove = ['foo', 'bar'],
result = arrayToRemove.reduce((total, key) => {
const { [key]: dummy, ...remainder } = total;
return remainder;
}, originalObj);
console.log(result);
这篇关于如何基于动态定义的变量解构对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!