0

I am trying to iterate through vales of properties of an object. here is my code

var player =
{

    name: 'kaka',
    age: 33,
    address: '22 green street',
    sayHello: function () {
        console.log('my name is ' + this.name + "my age is " + this.age);
    }
}

var myProperties = Object.keys(player);

for (var i = 0; i < myProperties.length; i++) {
    console.log(myProperties[i]);

}

But it only displays the properties and not values. How can i go through values like 'kaka' for name.. Thanks.

1
  • Why not doing for (var key in player) { var value = player[key]; } ? Commented Oct 23, 2015 at 3:01

2 Answers 2

1

You would need to use the keys as lookup in original object

for (var i = 0; i < myProperties.length; i++) {
    if(typeof player[myProperties[i]] !== 'function'){
            console.log(player[myProperties[i]]); 
    }  
}

In the end I'm not sure you gain much creating and iterating the keys vs using a for in loop for this use case

Sign up to request clarification or add additional context in comments.

3 Comments

Please tell me how it is done as i am a newbie. I mean player[myProperties[i]] .. why we use square brackets?
could do this same thing using for(var key in player){ console.log(player[key]} ...the [] are needed for variable property names
The benefit is that Object.keys only returns own enumerable properties of the object, whereas for..in returns all enumerable properties, including those on the [[Prototype]] chain.
0

Note that since Object.keys returns an Array, you can use an iterator like forEach for convenience:

Object.keys(player).forEach(function(key) {
  console.log(key + ': ' + player[key]);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.