Emerson Lopes
Emerson Lopes

Reputation: 119

React: set the state based on array values

I have an array of questions like this

[
  {
    title: 'what_are_your_hobbies',
  },
  {
    title: 'do_you_know_german',
  },
]

how can I iterate over this array and set its titles to the state like:

state = {
  what_are_your_hobbies: '',
  do_you_know_german: ''
}

Upvotes: 1

Views: 51

Answers (1)

Tholle
Tholle

Reputation: 112927

You could use reduce to iterate over the array and set all title to a key on the new object and use that to update your state.

Example

const arr = [
  {
    title: "what_are_your_hobbies"
  },
  {
    title: "do_you_know_german"
  }
];
const stateUpdate = arr.reduce((result, element) => {
  result[element.title] = "";
  return result;
}, {});

this.setState(stateUpdate);

Upvotes: 7

Related Questions