This question already has answers here:
How do I convert array of Objects into one Object in JavaScript?
                                
                                    (13个回答)
                                
                        
                        
                            Convert Javascript array of objects into one object
                                
                                    (4个答案)
                                
                        
                                5个月前关闭。
            
                    
我有一个对象数组

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}

最佳答案

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

09-11 19:01
查看更多