是否可以通过解构从数组创建对象? [重复]

问题描述 投票:0回答:2

这个问题在这里已有答案:

是否有可能做到这一点:

const foo = [1, 2];
const bar = {
    a: foo[0],
    b: foo[1],
    c: 'something else not in array'
};

作为单一陈述,避免申报foo

例如,数组可能是结果

"1, 2".split(', ')

并且您希望避免临时变量声明,使用"1""2"作为新对象中两个属性(可能不是唯一属性)的值。

我可以想象这样的事情,尽管由于各种原因两者都没有效果:

const bar { a, b, c: 'something else not in array' } = [1, 2];

要么

const bar { a:[0], b:[1], c: 'something else not in array' } = [1, 2];

编辑:我发现的最接近的,没有使用IIFE,是

Object.assign({c: 'something else not in array'}, [1, 2])

其中有一个负数,而不是名为'a'和'b'的属性,你得到名为'0'和'1'的属性:

{0: 1, 1: 2, c: "something else not in array"}
javascript arrays object ecmascript-6 destructuring
2个回答
1
投票

是的,使用IIFE:

 const bar = (([a, b]) => ({ a, b, c: "other props" }))([1, 2]);

0
投票

如果它只涉及两个属性/值,那么reduce也可以工作:

const bar = [1, 2].reduce((a, b) => ({ a, b, c: "other"}));
© www.soinside.com 2019 - 2024. All rights reserved.