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} 
3
  • 5
    What did you try? Why is there [] around the keys? for loop or reduce.... Commented Mar 21, 2019 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. Commented Mar 21, 2019 at 14:01
  • Did any of the answers work for you? Consider accepting one of them if that’s the case. Commented Mar 26, 2019 at 13:52

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.