Object.values to iterate JavaScript object properties

In JavaScript, you can display the values of all public enumerable properties of an object by using Object.values().

For instance, if you have an object like the one depicted below:


const Product = {
    name:"p1",
    price:100,
}

You can output the values of all properties by utilizing Object.values() like this:


let p = Object.values(Product);
console.log(p);


As an output, you get an array with property values as shown below,

[ ‘p1’, 100 ]

It’s crucial to understand that Object.values() only lists enumerable properties.

For instance, if you were to update the Product property to make ‘name’ not-enumerable, the output of Object. values () would change accordingly.


Object.defineProperty(Product, 'name', {enumerable: false});

let p1 = Object.values(Product);
console.log(p1);


As an output, you get an array with property values as shown below,

[100]

So some features of Object.values() are,

  1. It returns an array
  2. It returns only enumerable properties
  3. It returns properties in same order as they are in the object
  4. It does not return non-enumerable properties.

Let me know if you use Object.values() in your project.


Discover more from Dhananjay Kumar

Subscribe to get the latest posts sent to your email.

Published by Dhananjay Kumar

Dhananjay Kumar is founder of NomadCoder and ng-India

Leave a comment

Discover more from Dhananjay Kumar

Subscribe now to keep reading and get access to the full archive.

Continue reading