我有一些使用 forEach 循环遍历用户数组的代码。在该循环中,我再次使用 forEach 来循环其价格警报。看起来像这样
user_data.users.forEach((user, index) => {
if (user.id == id) {
user.price_alerts.forEach((alert, alert_index) => {
if (alert.symbol == symbol) {
//remove alert
user.price_alerts.splice(alert_index, 1);
}
});
}
});
但这样做的问题是,它并没有删除所有与“SYMBOL”匹配的内容,而是删除了一个。 我该如何解决 ?提前致谢<3
最佳答案
如果您需要删除所有不满足某些条件的元素,请尝试使用filter
方法:
let result = user.price_alerts.filter(alert => alert.symbol !== symbol);
更新:
user.price_alerts = user.price_alerts.filter(alert => alert.symbol !== symbol);
关于javascript - forEach 的替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62059795/