gpt4 book ai didi

javascript - 将对象推送到数组时,如何不推送相同的对象?

转载 作者:行者123 更新时间:2023-11-28 14:15:10 24 4
gpt4 key购买 nike

我正在使用复选框中选中的对象创建新数组。但是当我再次提交时,出现错误“flattenChildren(...):遇到两个具有相同 key 的子项,.$3。子项 key 必须是唯一的;当两个子项共享一个 key 时,只有将使用第一个 child 。”我只想推送唯一的对象。

我正在使用 react

handleSubmit(){

let students = []
for(let idx in this.state.checked){
if(this.state.checked[idx] ){
students.push(this.state.allStudent[idx])
}
}
console.log('students', students)
this.setState({
studentList: update(this.state.studentList, {$push: students})
})

}

最佳答案

当您使用 React 时,您应该能够安全地使用 ES6 Set 对象,它允许您存储任何类型的唯一值。 (https://devdocs.io/javascript/global_objects/set)。

例如

handleSubmit(){

let students = []
for(let idx in this.state.checked){
if(this.state.checked[idx] ){
students.push(this.state.allStudent[idx])
}
}

students = [...new Set(students)];

console.log('students', students)
this.setState({
studentList: update(this.state.studentList, {$push: students})
})

}

关于javascript - 将对象推送到数组时,如何不推送相同的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57819647/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com