【问题标题】:shortest way to create a comma separated object list [duplicate]创建逗号分隔的对象列表的最短方法[重复]
【发布时间】:2019-03-21 13:57:03
【问题描述】:

我有一个对象数组

const options = [
  { value: 'opt1', label: 'Lopt1' },
  { value: 'opt2', label: 'Lopt2' },
  { value: 'opt3', label: 'Lopt3' },
  { value: 'opt4', label: 'Lopt4' }
]

在 javascript/react 中创建对象列表的最短方法是什么

const result = {[Lopt1]: opt1, [Lopt2]: opt2, [Lopt3]: opt3, [Lopt4]: opt4}

【问题讨论】:

  • 你尝试了什么?为什么键周围有[]? for 循环或减少....
  • 请注意,您描述的结果不是“列表”;它只是一个对象。如果要控制名称/值对的顺序,则必须创建单独的对象并将它们排列在一个数组中。
  • 任何答案对您有用吗?如果是这种情况,请考虑 accepting one of them

标签: javascript reactjs


【解决方案1】:

您可以将reduce 与一个空对象的默认值一起使用,您可以使用label 作为键和value 作为值来构建该空对象。

const options = [
  { value: "opt1", label: "Lopt1" },
  { value: "opt2", label: "Lopt2" },
  { value: "opt3", label: "Lopt3" },
  { value: "opt4", label: "Lopt4" }
];

const result = options.reduce((acc, el) => {
  acc[el.label] = el.value;
  return acc;
}, {});

console.log(result);

【讨论】:

    【解决方案2】:

    您可以使用Array#reduceES6 destructuring assignment

    // extract value and label property 
    let res = options.reduce((obj, { value, label }) => {  
      // define the propery value
      obj[label] = value;
      //  return for next iteration
      return obj;
      // set initial value as an empty object
    }, {})
    

    const options = [{
        value: 'opt1',
        label: 'Lopt1'
      },
      {
        value: 'opt2',
        label: 'Lopt2'
      },
      {
        value: 'opt3',
        label: 'Lopt3'
      },
      {
        value: 'opt4',
        label: 'Lopt4'
      }
    ];
    
    let res = options.reduce((obj, { value, label }) => {
      obj[label] = value;
      return obj;
    }, {})
    
    console.log(res);

    使用ES6 spread syntax 更短。

    let res = options.reduce((obj, { value, label }) => ({ [label] : value, ...obj }), {});
    

    或者

    let res = options.reduce((obj, { value, label }) => (obj[label] = value, obj), {});
    

    const options = [{
        value: 'opt1',
        label: 'Lopt1'
      },
      {
        value: 'opt2',
        label: 'Lopt2'
      },
      {
        value: 'opt3',
        label: 'Lopt3'
      },
      {
        value: 'opt4',
        label: 'Lopt4'
      }
    ];
    
    let res = options.reduce((obj, {
      value,
      label
    }) => ({
      [label]: value,
      ...obj
    }), {});
    
    let res1 = options.reduce((obj, {
      value,
      label
    }) => (obj[label] = value, obj), {});
    
    console.log(res, res1);

    【讨论】:

      猜你喜欢
      • 2016-07-23
      • 2010-10-14
      • 1970-01-01
      • 1970-01-01
      • 2010-09-17
      • 1970-01-01
      • 2011-04-26
      • 2021-08-24
      • 2013-02-26
      相关资源
      最近更新 更多