0

I'm studying React and json objects, but I can't obtain what i want:

Here is the code:

const selectOptions1 = {
    9: 'good',
    14: 'Bad',
    26: 'unknown'
  };

  const selectOptions2 = options.map((item) => {
    return (
      { [item.value]:item.label }
    )
  })

  console.log(selectOptions1) // {9:good, 14:bad, 26:unknown}
  console.log(selectOptions2) // [{…}, {…}, {…}] -> 0: {9: "good"} 1: {14: "bad"} 2: {26: "unknown"}

How can I create an object like selectOptions1 using map (instead of the structure like in selectOptions2)?

1
  • what is options here? Commented Apr 13, 2021 at 15:36

1 Answer 1

1

you should use Reduce instead of map

const options = [
  {value: 1, label : 'one'},
  {value: 2, label : 'two'},
  {value: 3, label : 'three'},
  {value: 41, label : 'four'},
  {value: 32, label : 'five'},
]

var obj = options.reduce((accumulator, current) => {
  return {
    [current.value]: current.label,
    ...accumulator,
  }
}, {});

console.log(obj);

Because map transform every item into a new one and returns a list of the same length with the transformation applied. you are transforming every {value, label} object into a new {value, label} object.

reduce accumulates and returns only one result, that can be a list or something else if you have creativity with it, here i'm using the Spread operator to accumulate keys in one object.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.