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.
"k"
you're asking about come from? If you have areturn
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 thereturn
value from your function will beundefined
, becauseobj[key]
is undefined after the loop removes the last item.