Object.entries() Method – Copy an Object's Key-Value Pairs into an Array
Whenever you use Object.entries() on a JavaScript object, the method does the following:
- It creates a new array.
- It copies the specified object's enumerable own key-value pairs into the newly created array.
- It returns the new array containing one or more nested arrays. Each nested array has two items: the property's key (always represented as a string item) and the property's value.
Syntax of the Object.entries()
Method
Object.entries()
accepts a single argument. Here's the syntax:
Object.entries(objectArgument);
The objectArgument
refers to the JavaScript object whose key-value pairs you want to extract into a new array.
note
The Object.entries()
method does not alter the original object.
Examples of the Object.entries()
Method
Below are examples of the Object.entries()
method.
Copy an object's key-value pairs into a new array
const profile = {
firstName: "Oluwatobi",
lastName: "Sofela",
companyName: "CodeSweetly",
npmPackage: "@codesweetly/react-youtube-playlist",
id: 9103,
};
const formData = Object.entries(profile);
console.log(formData);
// The invocation above will return:
// [
// ["firstName", "Oluwatobi"],
// ["lastName", "Sofela"],
// ["companyName", "CodeSweetly"],
// ["npmPackage", "@codesweetly/react-youtube-playlist"],
// ["id", 9103],
// ]
Express Your Love for Coding!
Explore CodeSweetly's Shop for an array of stylish products to enhance your coding experience.
Click now to shopCopy an array's key-value pairs into a new array
const myBio = ["Oluwatobi", "Sofela", "CodeSweetly", 9103];
const itemsInMyBio = Object.entries(myBio);
console.log(itemsInMyBio);
// The invocation above will return:
// [
// ["0", "Oluwatobi"],
// ["1", "Sofela"],
// ["2", "CodeSweetly"],
// ["3", 9103],
// ]
Copy a string's key-value pairs into a new array
const firstName = "Oluwatobi";
const itemsInFirstName = Object.entries(firstName);
console.log(itemsInFirstName);
// The invocation above will return:
// [
// ["0", "O"],
// ["1", "l"],
// ["2", "u"],
// ["3", "w"],
// ["4", "a"],
// ["5", "t"],
// ["6", "o"],
// ["7", "b"],
// ["8", "i"],
// ]
The Object.entries()
method successfully extracted the string's key-value pairs because strings are the only primitive data with enumerable own properties.
tip
- Use
Object.keys()
to extract an object's keys (property names). - Use
Object.values()
to extract an object's values.
Overview
This article discussed what the Object.entries()
method is. We also used examples to see how it works.
Your support matters: Buy me a coffee to support CodeSweetly's mission of simplifying coding concepts.
Join CodeSweetly Newsletter