Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing object's keys and values

Tags:

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

like image 556
Dania Avatar asked May 10 '13 09:05

Dania


People also ask

What is key and value in object?

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.

How do I get a list of keys from an object?

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.

How do you know if an object has a key and value?

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 .


2 Answers

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]);
    }
});
like image 192
Juzer Ali Avatar answered Sep 21 '22 17:09

Juzer Ali


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]);
like image 33
James Allardice Avatar answered Sep 25 '22 17:09

James Allardice