Home > Web Front-end > JS Tutorial > body text

How to Convert a JavaScript Object into an Array of Key-Value Pairs?

Barbara Streisand
Release: 2024-11-27 08:36:09
Original
279 people have browsed it

How to Convert a JavaScript Object into an Array of Key-Value Pairs?

Converting an Object to an Array of Key-Value Pairs in JavaScript

In JavaScript, it is often necessary to convert an object into a more structured format, such as an array of key-value pairs. This conversion allows for easier manipulation and navigation of the data.

One common scenario where this conversion is useful is when working with JSON data. JSON objects are represented as strings and can be parsed into JavaScript objects. To convert an object into an array of key-value pairs, the following steps can be taken:

  1. Use Object.keys() method: This method returns an array containing the keys of the object.
  2. Use map() method: This method creates a new array by performing an operation on each element of the original array.

By combining these methods, you can easily convert an object into an array of key-value pairs. Here's an example:

var obj = { "1":5, "2":7, "3":0, "4":0, "5":0, "6":0, "7":0, "8":0, "9":0, "10":0, "11":0, "12":0 };
var result = Object.keys(obj).map((key) => [key, obj[key]]);

console.log(result);
Copy after login

Output:

[[1,5], [2,7], [3,0], [4,0]...]
Copy after login

As the output demonstrates, the object was successfully converted into an array of key-value pairs, where each element is a subarray containing the key and value of the original object.

The above is the detailed content of How to Convert a JavaScript Object into an Array of Key-Value Pairs?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template