在REACT JS中更新数组内容并删除重复项



你好,
我有以下问题。

我有两个数组。其中之一是存储来自API的项,它是这样的:

0: {id: '80682ddb-0785-ec11-94f7-281878bb3ca6', name: 'test', typeId: 14, typeName: 'typename', typeAbbreviation: 'asa'}
1: {id: '80682ddb-0785-ec11-94f7-212113ca6', name: 'number 2', typeId: 14, typeName: 'typename', typeAbbreviation: 'asa'}
2: {id: '80682ddb-0785-ec11-94f7-24124878bb3ca6', name: 'number 3', typeId: 14, typeName: 'typename', typeAbbreviation: 'asa'}

此数组中的值用于列出复选框。

第二个数组在用户每次单击其中一个复选框时更新。这个复选框被推到带有附加checked属性的表中:

0: {checked: true, id: '80682ddb-0785-ec11-94f7-281878bb3ca6', name: 'test', typeId: 14, typeName: 'typename', typeAbbreviation: 'asa'}

我的目标是将值推到表中-用所有复选框填充它,然后用选定的复选框替换特定的复选框。
一般情况下,Api中的值会被替换为特定的复选框值。

我尝试用几种方法来实现它,使用映射,过滤等等,像这样:

var newArray = [];
selectedItems?.forEach(function(mainObject) {
for (let i=0; i<currentItems.length; i++){
if(currentItems[i].id === mainObject.id){
newArray.push(mainObject);
} else {
newArray.push(currentItems[i])
}
}
});
我很感激你的帮助。有什么办法吗?

我所理解的是,您有一个来自API的列表,并且您希望将其显示为复选框,并且只获取用户选择的复选框。你可以使用地图。我认为你的方法是对的,你应该创建一个新的数组,而不是试图从原来的数组中删除项目。

const selectedItems = [];
const onChange = (e)=>{
let id = e.target.value;
if(e.target.checked){// if check box is selected
arrayFromApi.map(item => {
if(item.id === id){
selectedItems.push(item);
}
});
}else{// if checkbox is deselected
selectedItems.filter(item => item.id === id);     
}
}

最新更新