Understanding Object.values() in JavaScript with Examples
In JavaScript, `Object.values()` is a built-in method that returns an array containing the values of an object's properties. Here's an explanation with examples:
Example 1:
const myObject = { a: 1, b: 2, c: 3 };
const valuesArray = Object.values(myObject);
console.log(valuesArray);
Output:
[1, 2, 3]
In this example, `Object.values()` takes the `myObject` and returns an array containing the values `[1, 2, 3]`.
Example 2:
const person = { name: 'John', age: 30, city: 'New York' };
const valuesArray = Object.values(person);
console.log(valuesArray);
Output:
[’John’, 30, 'New York’]
In this example, `Object.values()` extracts the values from the `person` object, which are the strings `'John'` and `'New York'`, and the number `30`, and returns them as an array.
It's important to note that `Object.values()` only retrieves enumerable property values. Non-enumerable properties, or properties in the object's prototype chain, won't be included in the result.
If you want to include all properties, you might need to use a loop to manually gather the values, or use other methods like `for...in` or `Object.getOwnPropertyNames()`.
Remember that `Object.values()` is supported in modern JavaScript environments (ES2017+), so make sure your environment supports it if you intend to use it.