我有一个要存储在Redis密钥中的JSON字符串。每当将一个用户添加到另一个用户列表时,我都会向该键添加一个对象。如何删除名称属性与要删除的值匹配的对象。
[{"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":[]} ]
上面的字符串是我正在解析为allFriends
的Redis的结果。我还有一个变量exFriend
,它将保存名称属性之一的值。
是否可以删除名称属性等于"srtyt1"
的对象?还是需要重组数据?我在Mozilla的地图文档中看到了此循环,但我猜想它不适用于对象吗?
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;
}
}
答案 0 :(得分:0)
如果我正确理解了您的问题,则可以通过执行以下操作从需要friend.name === exFriend
条件的数组中“过滤”项目:
const exFriend = 'srtyt1';
const inputArray =
[{"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":[]} ];
const outputArray = inputArray.filter(item => {
return item.name !== exFriend;
});
console.log(outputArray);