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

IT技术 javascript reactjs
2021-05-09 08:05:45

我有一个对象数组

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个回答

您可以使用reduce一个空对象的默认值,该对象使用labelas 键和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);

您可以使用Array#reduceES6 解构赋值

// 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
}, {})

使用ES6 扩展语法更短

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

或者

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