Object.values() Method – Copy an Object's Values into an Array
Whenever you use Object.values() on a JavaScript object, the method does the following:
- It creates a new array.
- It copies the specified object’s enumerable own values into the newly created array.
- It returns the new array containing items representing the given object’s values.
Syntax of the Object.values()
Method
Object.values()
accepts a single argument. Here’s the syntax:
Object.values(objectArgument);
The objectArgument
refers to the JavaScript object whose values you want to extract into a new array.
Examples of the Object.values()
Method
Below are examples of the Object.values()
method.
Copy an object’s values into a new array
const profile = { firstName: "Oluwatobi", lastName: "Sofela", companyName: "CodeSweetly", npmPackage: "@codesweetly/react-youtube-playlist", id: 9103,};
const formValues = Object.values(profile);
console.log(formValues);
// The invocation above will return:// [ "Oluwatobi", "Sofela", "CodeSweetly", "@codesweetly/react-youtube-playlist", 9103 ]
Copy an array’s values into a new array
const myBio = ["Oluwatobi", "Sofela", "CodeSweetly", 9103];
const valuesInMyBio = Object.values(myBio);
console.log(valuesInMyBio);
// The invocation above will return:// [ "Oluwatobi", "Sofela", "CodeSweetly", 9103 ]
Copy a string’s values into a new array
const firstName = "Oluwatobi";
const valuesInFirstName = Object.values(firstName);
console.log(valuesInFirstName);
// The invocation above will return:// [ "O", "l", "u", "w", "a", "t", "o", "b", "i" ]
The Object.values()
method successfully extracted the string’s values because strings are the only primitive data with enumerable own properties.