2

I have a JSON Object something like this below :

   var users =  {
      ross: [
        {
          socket_id: 'K7XhUcIXAQFkmhK7AAAA',
          community_id: 2
        },
        {
          socket_id: 'gWBy0adi2e3KoIWuAAAC',
          community_id: 2
        },
        {
          socket_id: 'PRQ2czNZuvatsy8cAAAD',
          community_id: 2
        },
        {
          socket_id: 'R-EGVCDc5jWQV50KAAAF',
          community_id: 2
        }
      ],
      laura: [
        {
          socket_id: 'VCp2NxY42LMNvOclAAAE',
          community_id: 2
        },
        {
          socket_id: 'MDZe6Oe8U4xzmUjxAAAG',
          community_id: 2
        }
      ],
      john: [
        {
          socket_id: 'Omn3VQKyuYHm2JNdAAAH',
          community_id: 2
        }
      ]
    }

Now when socket is disconnected, I want to delete that socket object from that user's array. Now I have written a function to delete the Json Object from Json array.

var cleaner= function(arr, id) {
            for (var i = 0; i < users.length; i++) {
                var cur = users[i];
                if (cur.id === id) {
                    arr.splice(i, 1);
                    break;
                }
            }
        };
cleaner(users, socket.id);

The only problem with above funtion is that I need to pass the name of the key to which that JSON Array is of.

Basically, first I want to find the name of the key of that JSON Array and when I will get the key name I will pass it to cleaner function. But I don't know how to find the name of the key of the JSON Array.

4
  • Maybe you could use some Regex to find it and replace it with '' (emptyness). Not sure if it's the proper way of doing it but is sure would be effective. Commented Apr 10, 2017 at 7:19
  • cur.id === uniqueId where is id property coming from and what is uniqueId? Commented Apr 10, 2017 at 7:51
  • it is socket id which is passed in the function. I have edited the question. Sorry. Commented Apr 10, 2017 at 7:59
  • @shahakshay94 but curr still doesn't have the id property Commented Apr 10, 2017 at 8:00

2 Answers 2

2

With the given structure, you need to iterate over the keys of the object and then over the arrays inside.

var users = { ross: [{ socket_id: 'K7XhUcIXAQFkmhK7AAAA', community_id: 2 }, { socket_id: 'gWBy0adi2e3KoIWuAAAC', community_id: 2 }, { socket_id: 'PRQ2czNZuvatsy8cAAAD', community_id: 2 }, { socket_id: 'R-EGVCDc5jWQV50KAAAF', community_id: 2 }], laura: [{ socket_id: 'VCp2NxY42LMNvOclAAAE', community_id: 2 }, { socket_id: 'MDZe6Oe8U4xzmUjxAAAG', community_id: 2 }], john: [{ socket_id: 'Omn3VQKyuYHm2JNdAAAH', community_id: 2 }] },
    cleaner = function (object, socket_id) {
        Object.keys(object).some(function (k) {
            return object[k].some(function (a, i, aa) {
                if (a.socket_id === socket_id) {
                    aa.splice(i, 1);
                    return true;
                }
            });
        });
    };

cleaner(users, 'PRQ2czNZuvatsy8cAAAD');

console.log(users);
.as-console-wrapper { max-height: 100% !important; top: 0; }

More than one to delete approach with Array#filter.

var users = { '[email protected]': [ { socket_id: '4MIPKfkcitCV9xp6AAAA', community_id: 8 }, { socket_id: '4MIPKfkcitCV9xp6AAAA', community_id: 9 } ] } ,
    cleaner = function (object, socket_id) {
        Object.keys(object).forEach(function (k) {
            var temp = object[k].filter(function (a) {
                return a.socket_id !== socket_id;
            });
            if (object[k].length !== temp.length) {
                object[k] = temp;
            }
        });
    };

cleaner(users, '4MIPKfkcitCV9xp6AAAA');

console.log(users);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

4 Comments

Your answer worked perfectly fine but what happens in the scenario where there are same socket IDs and different community_id. I tested this but as I am using .some() it will return as soon as it will find the desired socket.id. var users = { '[email protected]': [ { socket_id: '4MIPKfkcitCV9xp6AAAA', community_id: 8 }, { socket_id: '4MIPKfkcitCV9xp6AAAA', community_id: 9 } ] } In this case both objects should be removed and '[email protected]' should be an empty array. How can we do that within .some function.
@shahakshay94, you need a different approach, because the first is looking only for one id, not for more than one. the second creates a new result set and check the length, if different, the new result set gets assigned to the property.
How about making it recursive. I added cleaner(users, socket.id); inside the if statement and removed the return true statement. It is working fine but is it the appropriate solution for this ?
the data structure does not look recursive to me.
1

try this (replace this with your for loop):

for(var i in users)
{
     name = i;
     array = users[i]
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.