This article is about how to use the `Object.values()` method in JavaScript. It explains what the method does, how to use it, and provides examples. Here's how to use `Object.values()` in JavaScript. What is `Object.values()`? The `Object.values()` method returns an array of a given object's own enumerable property values. Syntax: `Object.values(obj)` Parameters: `obj`: The object whose enumerable property values you want to get. Return value: An array containing the given object's own enumerable property values. How to use `Object.values()` Here are some examples of how to use `Object.values()`: Example 1: Getting the values of a simple object ```javascript const person = { name: "John Doe", age: 30, city: "New York" }; const values = Object.values(person); console.log(values); // Output: ["John Doe", 30, "New York"] ``` In this example, `Object.values()` is used to get an array of the values from the `person` object. The output is an array containing the name, age, and city. Example 2: Getting the values of an object with different data types ```javascript const car = { make: "Toyota", model: "Camry", year: 2022, isElectric: false }; const values = Object.values(car); console.log(values); // Output: ["Toyota", "Camry", 2022, false] ``` This example shows that `Object.values()` works with objects containing various data types, including strings, numbers, and booleans. Example 3: Using `Object.values()` with an empty object ```javascript const emptyObj = {}; const values = Object.values(emptyObj); console.log(values); // Output: [] ``` If you pass an empty object to `Object.values()`, you get an empty array. Example 4: Using `Object.values()` with an array Arrays are objects in JavaScript, so you can use `Object.values()` on them. ```javascript const fruits = ["apple", "banana", "cherry"]; const values = Object.values(fruits); console.log(values); // Output: ["apple", "banana", "cherry"] ``` When used on an array, `Object.values()` returns an array of the array's elements. Example 5: Using `Object.values()` with an object that has non-enumerable properties Non-enumerable properties are not included in the output. ```javascript const myObject = {}; Object.defineProperty(myObject, 'a', { value: 1, enumerable: true }); Object.defineProperty(myObject, 'b', { value: 2, enumerable: false }); const values = Object.values(myObject); console.log(values); // Output: [1] ``` Here, only the value of property `a`, which is enumerable, is included in the result. Property `b` is ignored because it is not enumerable. `Object.values()` is a straightforward method that helps you extract the values from an object into an array. You can use it in various scenarios where you need to work with the data contained within an object.
⚠️ كل الكويزات على موقع "كويز بالعربى" ترفيهية فقط، ولا تحتوي على أي وعود بالفوز أو الجوائز المادية.
Khaled Misbah
Khaled Misbah