数组的SetState

时间:2019-12-25 17:00:29

标签: javascript arrays reactjs react-native ecmascript-6

我有一个对象,该对象具有数组。我想将该数组的IDs的状态设置为该状态下的另一个空数组。我希望将array1[1].team.id推送到空数组array2并将状态设置为true。我的代码:

this.state: {

    array1: [
        {id:1, team: [
            {id:1, name: 'name1a'},
            {id:2, name: 'name2a'},
            {id:3, name: 'name3a'}
        ]},

        {id:2, team: [
            {id:1, name: 'name1b'},
            {id:2, name: 'name2b'},
            {id:3, name: 'name3b'}
        ]},

        {id:3, team: [
            {id:1, name: 'name1c'},
            {id:2, name: 'name2c'},
            {id:3, name: 'name3c'}
        ]},
    ],

    array2: [

    ]

}

所以有了这个功能,我希望array2是:

array2: [
   {id:1, status:true},
   {id:2, status:true},
   {id:2, status:true}
]

我尝试过:

updateArray = (id) => {     //consider id=1

    let array2 = [...this.state.array2];

    let newArray2 = [...this.state.array1[id].team.id, status:true];

    this.setState({
        array2: newArray2
    })

}

它没有用。显然,做错了事。我该怎么做?谢谢。

1 个答案:

答案 0 :(得分:0)

array1[id]上使用地图功能:

updateArray = id => {
    const array2 = this.state.array1[id].team.map(item => (
        {id: item.id, status: true}
    ));
    this.setState({array2})
}

我不知道您是否总是要替换array2中的值,还是需要根据传递给state的{​​{1}}来在id中创建多个新数组。以上功能,例如array2array3等?

更新:如果id与父数组的索引不同(如 adiga Chris )

updateArray = id => {
    const arrayToConsider = this.state.array1.find(element => (
        element.id === id
    ));
    const array2 = arrayToConsider.team.map(item => (
        {id: item.id, status: true}
    ));
    this.setState({array2})
}