Prajakta A
Prajakta A

Reputation: 68

Removing values from object of arrays modifies the entire object even when iterated over keys

Performing operations on object of arrays:

-----code -------

 var obj1 = { 'a': ['a','b','c','d'], 'b':['b','d','r','a']}
    Object.keys(obj1).forEach(element => {
        var range = obj1[element].indexOf(element);
        if (range !== -1) {
            obj1[element].splice(range, 1);
        }});
    
    Result: {
        "a": [  "c",  "d" ],
        "b": [ "d","r"]
    }

Upvotes: 2

Views: 49

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386710

You could search for the index and remove the unwanted key.

var object = {
  a: ['a', 'b', 'c', 'd'],
  b: ['b', 'd', 'r', 'a']
};

Object.keys(object).forEach((key, _, keys) => {
    var index;
    while ((index = object[key].indexOf(key)) !== -1)
        object[key].splice(index, 1);
});

console.log(object);

Upvotes: 2

Related Questions