I want to print a key: value pair from javascript object. I can have different keys in my array so cannot hardcode it to object[0].key1
var filters = [{"user":"abc"},{"application":"xyz"}];
console.log(Object.keys(filters[0])[0]); // prints user
var term = (Object.keys(filters[0])[0]);
console.log(filters[0].term); // prints undefined
How can i print the value of the key
The keys of an object is the list of property names. The values of an object is the list of property values. The entries of an object is the list of pairs of property names and corresponding values.
For getting all of the keys of an Object you can use Object. keys() . Object. keys() takes an object as an argument and returns an array of all the keys.
You can use the JavaScript in operator to check if a specified property/key exists in an object. It has a straightforward syntax and returns true if the specified property/key exists in the specified object or its prototype chain. Note: The value before the in keyword should be of type string or symbol .
for (var key in filters[0]){
console.log( key + ": " + filters[0][key]);
}
Or if you want to print all the values of filters
for (var i in filters){
console.log(i);
for (var key in filters[i]){
console.log( key + ": " + filters[i][key]);
}
}
##On @mplungjan 's comment
filters.forEach(function(obj, index){
console.log(index);
for (var key in obj){
console.log(key, obj[key]);
}
});
This is looking for a term
property on filters[0]
:
console.log(filters[0].term);
What you actually want to do is use the value of term
(in your example that will be "user"
) as the property identifier:
console.log(filters[0][term]);
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