sopstem2428
sopstem2428

Reputation: 11

How to remove array values from an object

var obj = {
a: [1, 3, 4],
b: 2,
c: ['hi', 'there']
   }
   removeArrayValues(obj);
   console.log(obj); // --> { b: 2 }

Here is my code:

function removeArrayValues(obj) {
 for (var key in obj){
 if (Array.isArray(obj[key])) delete obj[key]
 //return obj[key] -> {b: 2, c: ["hi", "there"]}
 }
 return obj[key]
}

Why does it return only obj["a"] and obj["c"] when I return it inside the for/in loop and not obj["k"]. I figured the problem out right before I was about to post this but I run into this issue a lot with both arrays and objects and could use an explanation of what is going on here.

Upvotes: 0

Views: 889

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

First, let's see your object. It has 3 key/value pairs:

var obj = {
    a: [1, 3, 4],//the value here is an array
    b: 2,//the value here is not an array
    c: ['hi', 'there']//the value here is an array
};

For each key in that object, your removeArrayValues function will delete any of them which has an array as value:

if (Array.isArray(obj[key]))

That condition will return "true" if the value is an array. You can check this in this demo: the console.log inside the for loop will log "true", "false" and "true":

var obj = {
a: [1, 3, 4],
b: 2,
c: ['hi', 'there']
   }
   removeArrayValues(obj);

function removeArrayValues(obj) {
 for (var key in obj){
 console.log(Array.isArray(obj[key]))
 if (Array.isArray(obj[key])) delete obj[key]
 //return obj[key] -> {b: 2, c: ["hi", "there"]}
 }
 return obj[key]
}

So, the first key will be removed ("true"), the second one will not ("false"), and the third one will be removed ("true").

Upvotes: 2

Related Questions