I have a Javascript object with some keys and values:
var obj = {
"key1" : "val1",
"key2" : "val2",
"key3" : "val3",
"key4" : ""
}
I want to iterate all keys and retrieving all values.
I tried 2 ways:
1) Using for(var key in keys)
var keys = Object.keys(obj);
for (var key in keys) {
// ...
}
The problem with this solution is that keys object is an array, so I have to use obj[keys[key]]]. Not very pretty.
Furthermore, inspecting "key4", the return value is "0" instead of "" (empty).
2) Using forEach
Object.keys(obj).forEach(function(key){
// ...
});
The problem in this case is that if I try to do:
Object.keys(obj).forEach(function(key){
obj[key]; // <- obj is undefined !!
});
The "obj" variable is undefined in the foreach!
What's the best way to iterate in all keys for retrieving all values?
Thanks