0

Why does this code run without errors, but not delete anything from obj?

function removeEvenValues(obj) {
       for (i=0; i < obj.length;++i)
          if (obj[i].value%2===0)
            delete obj[i];
            return obj;
}

const obj = {a:1, b:2 ,c:3, d:4}
const res = removeEvenValues(obj);

console.log(res);

6
  • Because the way you are iterating over object is incorrect!!. If your obj is an array then access elements like obj[i].value. To iterate over object use for key in obj Commented Oct 22, 2018 at 20:34
  • What is the type of obj? from the snippet, it doesn't look like an array and hence you can't loop. Did you mean if (obj[i].value%2===2)? Commented Oct 22, 2018 at 20:36
  • Please edit the question to include an example of obj it's really difficult to help if we don't know what that looks like. Commented Oct 22, 2018 at 20:37
  • Your obj is not avid javascript. Is it supposed to be: obj ={a:1,b:2,c:3,d:4}? Commented Oct 22, 2018 at 20:40
  • sorry, coming from python... Commented Oct 22, 2018 at 20:41

1 Answer 1

1

Unlike Python you can't just iterate the length of an object because obj.length === undefined. You can use Object.keys() to get an array of keys. Then you can iterate them:

obj = {a:1,b:2,c:3,d:4}

function removeEvenValues(obj) {
       Object.keys(obj).forEach(key =>{
        if (obj[key] % 2 ===0)
            delete obj[key];
       })  
       return obj;
}

console.log(removeEvenValues(obj))

or you can also use for...in:

obj = {a:1,b:2,c:3,d:4}

function removeEvenValues(obj) {
   for(let key in obj){
     if (obj[key] % 2 ===0)
         delete obj[key];
     }
     return obj
}

console.log(removeEvenValues(obj))

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

2 Comments

Is for (i = 0; i < obj.length; ++i) not a preferred method anymore in jS?
@Guar for loops are fine. The problem is that objects don't have a length. obj.length === undefined.

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.