0
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.

3
  • 1
    It's not clear what you didn't understand. The if returns "true", "false" and "true". Commented Oct 28, 2016 at 1:57
  • 1
    "and not obj["k"]" - Where does the "k" you're asking about come from? If you have a return statement inside the loop as per the line that you've commented out, then that exits the function immediately without completing the loop. Note that the return value from your function will be undefined, because obj[key] is undefined after the loop removes the last item. Commented Oct 28, 2016 at 1:59
  • What I can see is that you have successfully removed all object keys that contain the value of array.. What's the question again? Commented Oct 28, 2016 at 2:00

1 Answer 1

2

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").

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

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.