1

I have an object array

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

what is the shortest way to create a an object list in javascript/react

const result = {[Lopt1]: opt1, [Lopt2]: opt2, [Lopt3]: opt3, [Lopt4]: opt4}
Kimaya
  • 1,210
  • 4
  • 14
  • 33
  • 5
    What did you try? Why is there [] around the keys? for loop or reduce.... – epascarello Mar 21 '19 at 13:58
  • 1
    Note that your result as you describe it is not a "list"; it's just an object. If you want to control the ordering of the name/value pairs, you'll have to create separate objects and arrange them in an array. – Pointy Mar 21 '19 at 14:01
  • Did any of the answers work for you? Consider [accepting one of them](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work#answer-5235) if that’s the case. – Tholle Mar 26 '19 at 13:52

2 Answers2

2

You could use reduce with a default value of an empty object that you build up with the label as keys and value as values.

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);
Tholle
  • 108,070
  • 19
  • 198
  • 189
1

You can use Array#reduce and ES6 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);

Much more shortest by using ES6 spread syntax.

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

Or

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);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188