简体   繁体   English

将对象推入数组时,如何不将同一对象推入数组?

[英]When pushing objects to array, how to not push same object?

I'm creating new array with objects checked in the checkbox. 我正在使用复选框中选中的对象创建新数组。 But when i submit again, there's a error "flattenChildren(...): Encountered two children with the same key, .$3 . Child keys must be unique; when two children share a key, only the first child will be used." 但是,当我再次提交时,出现错误“ flattenChildren(...):遇到两个具有相同键的子项.$3子键必须是唯一的;当两个子项共享一个键时,只会使用第一个子项。” I want push only unique objects. 我只想推送唯一的对象。

I`m using 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})
    })

}

As you are using React, you should be able to safely use the ES6 Set Object, which lets you store unique values of any type. 使用React时,您应该能够安全地使用ES6设置对象,该对象可以存储任何类型的唯一值。 ( https://devdocs.io/javascript/global_objects/set ). https://devdocs.io/javascript/global_objects/set )。

eg 例如

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})
})

} }

I am not an expert in React.js, but this seems to be a simple problem(pushing only unique elements to a JS array). 我不是React.js的专家,但这似乎是一个简单的问题(仅将唯一元素推入JS数组)。 Your function modified as follows should work: 修改如下的函数应该可以工作:

handleSubmit(){
    let students = [...this.state.studentList];
    for(let idx in this.state.checked){
        if(this.state.checked[idx] && (students.indexOf(this.state.checked[idx]) === -1)){
            students.push(this.state.allStudent[idx])
        }
    }
    console.log('students', students)
    this.setState({
        studentList: update(this.state.studentList, students)
    })
}

What we have essentially done here is use the 'indexOf()' method on the 'students' array to check if the current element exists in the array - the indexOf() method returns -1 if an element is not found in an array. 我们在这里所做的基本上是在'students'数组上使用'indexOf()'方法检查数组中是否存在当前元素-如果在数组中找不到元素,则indexOf()方法将返回-1。 Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM