【问题标题】:JavaScript: Remove object whose property === value [duplicate]JavaScript:删除属性===值的对象[重复]
【发布时间】: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


【解决方案1】:

如果我正确理解您的问题,您可以通过执行以下操作从数组中“过滤”需要您的 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);

【讨论】:

  • 这肯定会奏效,它为我留下了空间,可以轻松地将旧数组保存为以前的朋友或类似的东西。谢谢!
  • 不客气! :)
猜你喜欢
  • 2015-12-14
  • 2015-11-21
  • 2011-12-28
  • 1970-01-01
  • 1970-01-01
  • 2020-11-03
  • 2016-11-08
  • 2018-03-28
  • 1970-01-01
相关资源
最近更新 更多