简体   繁体   中英

How do I delete a value from an object based on criteria in javaScript

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); 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM