创建逗号分隔的对象列表的最快捷方法

时间:2019-03-21 13:57:03

标签: javascript reactjs

我有一个对象数组

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}

2 个答案:

答案 0 :(得分:2)

您可以使用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);

答案 1 :(得分:1)

您可以使用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);