shakell
shakell

Reputation: 351

when key is unknown, how to get the value

Look this for example

var obj = {"name1":"jack"}; 
var key = "name1"; //get it by a function 
var value = obj.key;//get undefined 
value = obj.name1;//get "jack" 

If I don't kwon the key, here is name1. But I can get "name1" by a function. how I can get the value "jack".

Thanks.

Upvotes: 1

Views: 66

Answers (2)

Samsimus12
Samsimus12

Reputation: 28

If you need a function to loop through your object and log it's keys with their respective values you could do this:

var object = { name1: "Jack"};
function getValues(obj) {
    var keys = Object.keys(obj);
    for (var k in keys) {
        //This will print out the key as well as the value
        //Where keys[key] = key and obj[keys[key]] is the value
        console.log("Key: " + keys[k] + "\nValue: " + obj[keys[k]]);
    } 
}
getValues(object);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386868

You could take Object.keys for an array with all enumerable keys of the object. Then iterate the array and access the property of the object by using bracket notation (property accessor).

var object = { name1: "jack" },
    keys = Object.keys(object);

keys.forEach(key => console.log(object[key]));

Upvotes: 2

Related Questions