[英]using .filter to delete an item from an array of objects with react/javascript
I am using .filter function of javascript to delete an element by it's ID in TypeMp3List from this array of objects. 我正在使用javascript的.filter函数来从这个对象数组中删除TypeMp3List中的ID。 The format is like this :
格式如下:
The format I want to get after doing the filter when deleting for example the MP3 with ID:33390
is this : 在删除例如
ID:33390
的MP3时,我想在进行过滤后得到的格式是这样的:
This is the code I've built so far : 这是我到目前为止构建的代码:
showDeleteConfirmation(value, id, index, thisHandler) {
confirm({
title: 'Voulez vous supprimer cette audio ?',
content: '',
okText: 'Oui, je confirme',
okType: 'danger',
cancelText: 'Non',
onOk() {
deleteMp3Request(id);
var { extraitMP3 } = thisHandler.state;
var array = [];
for (var key in extraitMP3) {
array.push(extraitMP3[key]);
}
console.log('array',array)
const result = array.map(d => ({
...d,
TypeMp3List:
Object.fromEntries(
Object.entries(d.TypeMp3List).filter(index => index !== id)
)
}))
console.log('result',result)
thisHandler.setState({result: result})
NotificationManager.success("le fichier audio est supprimé avec succès !", "");
},
onCancel() {
},
});
}
Problem is after mapping and filtering the console.log(result)
is giving me the same results of console.log(array)
. 问题是在映射和过滤
console.log(result)
给出了与console.log(array)
相同的结果。 It looks like there is something wrong with the mapping and filtering and don't know exactly whats is it. 看起来映射和过滤有问题,并不知道它到底是什么。 any help would be appreciated.
任何帮助,将不胜感激。
Because you use Object.entries
- this returns a two-dimensional array (eg an array containing arrays), and within your filter
you're checking if each array is equal to a number. 因为你使用
Object.entries
- 这会返回一个二维数组(例如一个包含数组的数组),并且在你的filter
你要检查每个数组是否等于一个数字。 It isn't. 事实并非如此。 You want to access the first element of this array - so either a little destructuring:
你想访问这个数组的第一个元素 - 所以要么稍微解构:
Object.entries(d.TypeMp3List).filter(([index]) => index !== id)
Or more verbose array notation: 或者更详细的数组表示法:
Object.entries(d.TypeMp3List).filter(index => index[0] !== id)
since you want a new array based on .filter verification, try returning the result of what you are comparing: 既然您想要一个基于.filter验证的新数组,请尝试返回您要比较的结果:
Object.fromEntries(
Object.entries(d.TypeMp3List).filter((index) => {
return index !== id
)};
)
I think you made a mistake in using filter
function. 我认为你在使用
filter
功能时犯了一个错误。
In my opinion, you can pass each item to filter function and use its id
to compare with filterId
. 在我看来,您可以将每个项目传递给过滤器函数并使用其
id
与filterId
进行比较。
showDeleteConfirmation(value, filterId, index, thisHandler) {
...
Object.entries(d.TypeMp3List).filter(listItem => listItem.id !== filterId)
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.