Possible Duplicate:
How do I enumerate the properties of a javascript object?
If I have a javascript object like this :
data = {
a : 2,
b : 3
}
but a and b are arbitrary and decided at runtime. Is there any way to go through the object and access all properties without knowing the key?
How to get all property values of a JavaScript Object (without knowing the keys) ? Method 1: Using Object. values() Method: The Object. values() method is used to return an array of the object's own enumerable property values.
In JavaScript, an object consists of key-value pairs where keys are similar to indexes in an array and are unique. If one tries to add a duplicate key with a different value, then the previous value for that key is overwritten by the new value.
Use bracket notation to access a key that contains a space in an object, e.g. obj['my key'] . The bracket [] notation syntax allows us to access an object's key, even if it contains spaces, hyphens or special characters.
data = {
a : 2,
b : 3
}
for(var propName in data) {
if(data.hasOwnProperty(propName)) {
var propValue = data[propName];
// do something with each element here
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With