将JavaScript数组分解为现有对象的计算属性名称

问题描述 投票:-1回答:2

问题

说我们有一个值数组:

const values = [ 10, 20, 30 ];

说我们有一个要拾取这些值的对象:

let props = {
    "hello": null,
    "world": null,
    "other": null
};

我可以简单地做到这一点:

props.hello = values[0];
props.world = values[1];
props.other = values[2];

这样,我们最终将获得所需的结果:

console.log(props.hello); // Result: 10
console.log(props.world); // Result: 20
console.log(props.other); // Result: 30

或更准确地说:

console.log(props);
// Result:
// {
//      "hello": 10,
//      "world": 20,
//      "other": 30
// }

问题是我并不总是知道属性的名称是什么。

假设props是一个现有的但空的对象(或者,如果它确实包含属性,则它们与我们在此处执行的操作无关)。

props = {};

并且假设我们要根据一些相关值来计算每个属性的名称。

如何用所需的名称和值填充props

一种解决方案

因此,我可以这样做,将名称数组简化为一个对象,然后将该对象的属性分配回原始对象:

const names = [ "hello", "world", "other" ];
const newProps = names.reduce((p, c, i) => {
    p[c] = values[i];
    return p;
}, {});

props = Object.assign({}, props, newProps);

但是这看起来很混乱。对于其中一个,它假设i中存在的每个values都等同于names

问题

是否有办法通过销毁任务来做到这一点?

是的,如果我事先知道属性的名称,则:

[ props.hello, props.world, props.other ] = values;

但是,如果名称分别存在或需要在将名称分配给props对象之前进行计算该怎么办?

let props = {};
const values = [ 10, 20, 30 ];
const names = [ "hello", "world", "other" ];
// [ ...props??? ] = values;
//
// Desired result (props):
// {
//      "hello": 10,
//      "world": 20,
//      "other": 30
// }

[另一件事:除了表格的简洁性之外,我对销毁结构感兴趣的原因是,我希望namesvalues一经声明就被视为“不可变的”。理想情况下,对象props将是代码中唯一的更改状态。 (我通过用names声明valuesconst以及用props声明let来暗示这一点,尽管我知道实际上这些声明并不会阻止对象和数组的内容被更改。)

javascript destructuring
2个回答
2
投票

您可以同时迭代名称和值以进行分配。

let values = [10, 20, 30],
    props = {},
    names = ["hello", "world", "other"];

for (props[names.shift()] of values) ;

console.log(props);

0
投票

预期结果可如下获得:

let values = [ 10, 20, 30 ];
let names = [ "hello", "world", "other" ];
let props = {};

names.forEach((name, index) => props[name] = values[index]);
console.log(props);
© www.soinside.com 2019 - 2024. All rights reserved.