JavaScript Basics: Object.keys, Object.values, and Object.entries

in #javascript6 years ago

When you call the function Object.keys on an object, it returns an array containing the names of the given object's own, enumerable properties. Contrary to the for...in loop, the inherited properties are not included in the result.

On the other hand, Object.values returns an array containing the values of the given object's own, enumerable properties.

Similarly, Object.entries returns an array which contains the own, enumerable properties of the given object as name and value pairs. Each entry is a two-element array, containing the name and value of a property.

Here is an example:

    let ali = {
        name: "Ali",
        age: 19,
    };

    console.log(Object.keys(ali));    // [ 'name', 'age' ]
    console.log(Object.values(ali));  // [ 'Ali', 19 ]
    console.log(Object.entries(ali)); // [ [ 'name', 'Ali' ], [ 'age', 19 ] ]

In a for...in loop, all the properties in the prototype chain are included in the loop. So if you want to only iterate over own properties, you have to use the hasOwnProperty method or use Object.keys instead.


Related Posts

Sort:  

your effort on java is nice. it is informative

simple but useful .. thanks

valuable post for me. Thank you sir.

that is very helpful post...thank you so much

valuable post for me. Thank you sir.

I am impressed by your knowledge of Java Script language. Keep posting and let us know about Java in an easy to learn way. Thanks.

Bisyar khub...

@ghasemkiani WOW. Awesome tutorial. Thanks for sharing. Keep sharing please.

You help us too much, and that's why we learn, make a good contribution and work in this community. You can check my blog and support me with a vote of yours if you like

Excellent informative post for all steemians .Thanks for the sharing informative post. DQmRzwKEGxx96F5rqDP1PsQq3cxAK8GTWvrTtHMG51XMo54_1680x8400.jpeg

Coin Marketplace

STEEM 0.33
TRX 0.11
JST 0.034
BTC 66579.21
ETH 3282.19
USDT 1.00
SBD 4.30