1

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: ''
}
2
  • do you always want to set empty string as value? Commented Jul 30, 2018 at 13:35
  • mostly, sometimes I'd like to set some to arrays, but I can do it with setState and add values. Is that a problem if I set it to an empty string first? Commented Jul 30, 2018 at 22:48

1 Answer 1

7

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);
Sign up to request clarification or add additional context in comments.

1 Comment

@SungKim Thanks Sung! Glad to hear it.

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.