Destructure array to object property keys

前端 未结 6 1543
渐次进展
渐次进展 2020-12-15 18:40

I have an array of values like:

const arr = [1,2,3];

Is there any way I can use destructuring to create the following output? If not, what

相关标签:
6条回答
  • 2020-12-15 18:47

    You can achieve it pretty easily using lodash's _.zipObject

    const obj = _.zipObject(['one','two','three'], [1, 2, 3]);
    console.log(obj); // { one: 1, two: 2, three: 3 }
    
    0 讨论(0)
  • 2020-12-15 18:48

    Using destructuring assignment it is possible to assign to an object from an array

    Please try this example:

    const numbers = {};
    
    [numbers.one, numbers.two, numbers.three] = [1, 2, 3]
    
    console.log(numbers)

    The credit to the boys of http://javascript.info/ where I found a similar example. This example is located at http://javascript.info/destructuring-assignment in the Assign to anything at the left-side section

    0 讨论(0)
  • 2020-12-15 18:58

    You can assign destructurings not only to variables but also to existing objects:

    const arr = [1,2,3], o = {};    
    ({0:o.one, 1:o.two, 2:o.three} = arr);
    

    This works without any additional variables and is less repetitive. However, it also requires two steps, if you are very particular about it.

    I'm not sure if this helps, since you mentioned computed properties?!

    0 讨论(0)
  • 2020-12-15 19:02

    I don't believe there's any structuring/destructuring solution to doing that in a single step, no. I wanted something similar in this question. The old := strawman proposal doesn't seem to have legs in the new proposal list, so I don't think there's much activity around this right now.

    This answer shows a very neat two-step version.

    But if it's two steps, you may as well use a simple object initializer:

    const arr = [1,2,3];
    const obj = {
      one: arr[0],
      two: arr[1],
      three: arr[2]
    };
    console.log(obj);

    0 讨论(0)
  • 2020-12-15 19:06

    With destructuring, you can either create new variables or assign to existing variables/properties. You can't declare and reassign in the same statement, however.

    const arr = [1, 2, 3],
        obj = {};
    
    [obj.one, obj.two, obj.three] = arr;
    console.log(obj);
    // { one: 1, two: 2, three: 3 }

    0 讨论(0)
  • 2020-12-15 19:11

    This answers a slightly different requirement, but I came here looking for an answer to that need and perhaps this will help others in a similar situation.

    Given an array of strings : a = ['one', 'two', 'three'] What is a nice un-nested non-loop way of getting this resulting dictionary: b = { one : 'one', two: 'two', three: 'three' } ?

    const b = a.map(a=>({ [a]: a })).reduce((p, n)=>({ ...p, ...n }),{})

    0 讨论(0)
提交回复
热议问题