2

I have a JSON string which I am storing in a Redis key. I add an object to this key whenever a user is added to another users list. How can I remove that object whose name property matches the value to be removed.

[{"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":[]} ]

The above string is the result from Redis which I am parsing into allFriends. I also have a variable exFriend which will hold the value of one of the name properties.

Is there a way to remove the object whose name property equals "srtyt1"? Or will I need to restructure my data? I saw this loop in the Mozilla docs for maps, but I guess it does not work with objects?

    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;
      }
    }
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
Pfrex
  • 159
  • 2
  • 13

1 Answers1

0

If I understand your question correctly, you can "filter" items from the array that need your friend.name === exFriend criteria by doing the following:

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);
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65