如何在状态中遍历相似对象并将其推入对象?

时间:2019-03-27 13:43:28

标签: javascript reactjs

我的this.state对象中有几个变量:

this.state = {
      draw_number: '',
      user_number_1: '',
      user_number_2: '',
      user_number_3: '',
      user_number_4: '',
      user_number_5: '',
      user_number_6: '',
    }

如何遍历它们并将它们添加到以下对象中:

results {
  numbers: [],
  draws: x
}

这是我当前的解决方案:

 this.state = {
      draw_number: '',
      user_number_1: '',
      user_number_2: '',
      user_number_3: '',
      user_number_4: '',
      user_number_5: '',
      user_number_6: '',
    }
  }

  submitHandler = () => {
    let results = {};
    for (let i=1; i<=6; i++) {
      results = this.state['user_number_' + i];
    }
    console.log(results);
  }

现在我不能console.log我的“结果”对象

2 个答案:

答案 0 :(得分:4)

您可以从状态中提取draw_number属性,并将其用作draws,然后在状态中的其余属性上使用Object.keys,并将这些值用作{{ 1}}数组。

numbers

答案 1 :(得分:0)

您可以使用[spread运算符] [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax]。 这样,您可以从对象复制所有键(ECMAScript 2018中的新增功能):

const myFriend = {name: 'George', age: 12}
const mySuperFriend = { ...myFriend, superpowers: true }

注意 您不应该在react中直接改变状态对象。 而是创建一个新对象并setState