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;
      }
    }
3
  • 4
    data = data.filter(o => o.name !== 'srtyt1'). Commented Apr 6, 2019 at 4:29
  • 1
    or it you need to do it in place: allFriends.splice(allFriends.findIndex(o => o.name = "srtyt1"), 1) Commented Apr 6, 2019 at 4:31
  • Splicing exFriends sounds sinister! Commented Apr 6, 2019 at 4:34

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

2 Comments

That will definitely work and it leaves room for me to easily save the old array as former friends or something of that nature. Thanks!
You're welcome! :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.