ghasemkiani avatar

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

ghasemkiani

Published: 02 Feb 2018 › Updated: 02 Feb 2018JavaScript Basics: Object.keys, Object.values, and Object.entries

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

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

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

Written by

Read more #javascript posts


Best Posts From ghasemkiani

We have not curated any of ghasemkiani's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From ghasemkiani