remove an object from an array is not working properly,but it add object perfectly
const addItem =(selected)=>{
let data = selectedItems ? [...selectedItems] : [];
if (data.length) {
let index = data.indexOf(selected);
console.log(index);
if (index !== -1) {
data.splice(index, 1);
setSelectedItems(data);
} else {
data.push(selected);
}
} else {
data.push(selected);
}
console.log("selected", selectedItems);
setSelectedItems(data);
}
render button function add or remove on click it
<div className="file-list">
<MappedElement
data={[{ _id: 1 }, { _id: 2 }]}
renderElement={(value, index, arr) => {
let check=selectedItems.some((obj) => obj._id === value._id);
console.log("check", check);
return (
<DocumentCard key={index} className={file-list-item ${check ?
"active" : ""}}
onClick={() => addItem(value, arr, index)} /> ); }} />
</div>
Use
const addItem =(selected)=>{
let data = selectedItems ? [...selectedItems] : [];
if (data.length) {
let index = data.findIndex(value => value._id === selected._id)ж
console.log(index);
if (index !== -1) {
data.splice(index, 1);
} else {
data.push(selected);
}
} else {
data.push(selected);
}
console.log("selected", selectedItems);
setSelectedItems(data);
}
Your problem is probably in indexOf
method you're using.
You can not use this to find objects in your array.
There are several options you can use. You can use find or findIndex and pass a callback to find an object by the specified (preferably unique property of the object).
Example
let found = data.findIndex(item => item.id === selected.id);
For a selectedItems
array that looks like:
const selectedItems = [
{ _id: 1, /* other fields */ },
{ _id: 2, /* other fields */ },
{ _id: 3, /* other fields */ },
/* other objects */
];
And a selected
object that looks like:
const selected = { _id: 1 };
In order to perform the desired behavior, which is: if the element exists, remove it, else, add it , you can write the following:
// copy selected items with a fail-safe empty array
const data = selectedItems ? [...selectedItems] : [];
// find index of selected element
const removalIndex = data.findIndex(({ _id }) => (_id === selected._id));
// if selected element exists in data array, remove it
if (removalIndex !== -1) {
data.splice(removalIndex, 1);
}
// if selected element doesn't exist in data array, add it
else {
data.push(selected);
}
// update selected elements
setSelectedItems(data);
NOTE: if your array of selected items contains duplicates, meaning multiple objects that contain the same value for _id
, then this approach will be removing only the first instance of those. If you want to remove all of them, you'll have to use a loop or recursivity.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.