【发布时间】:2019-08-27 23:28:28
【问题描述】:
我有一个存储在 Redis 键中的 JSON 字符串。每当将用户添加到另一个用户列表时,我都会向此键添加一个对象。如何删除 name 属性与要删除的值匹配的对象。
[{"name":"srtyt1","wins":0,"losses":0,"levels":0,"color":1672960,"avatar":[]},
{"name":"srtyt2","wins":0,"losses":0,"levels":0,"color":1672960,"avatar":[]},
{"name":"srtyt3","wins":0,"losses":0,"levels":0,"color":1672960,"avatar":[]} ]
以上字符串是 Redis 的结果,我将其解析为 allFriends。我还有一个变量exFriend,它将保存名称属性之一的值。
有没有办法删除name属性等于"srtyt1"的对象?还是我需要重组我的数据?我在 Mozilla docs for maps 中看到了这个循环,但我猜它不适用于对象?
let allFriends = JSON.parse(result);
//iterate through all friends until I find the one to remove and then remove that index from the array
for (let [index, friend] of allFriends) {
if (friend.name === exFriend) {
//remove the friend and leave
allFriends.splice(index, 1);
break;
}
}
【问题讨论】:
-
data = data.filter(o => o.name !== 'srtyt1'). -
或者你需要在原地做:
allFriends.splice(allFriends.findIndex(o => o.name = "srtyt1"), 1) -
拼接exFriends听起来很邪恶!
标签: javascript json