Home > Web Front-end > JS Tutorial > How Can I Convert a JavaScript Object into an Array of Key-Value Pairs?

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

DDD
Release: 2024-12-10 00:59:10
Original
653 people have browsed it

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

Transforming Objects into Key-Value Pair Arrays in JavaScript

In the world of JavaScript, converting objects into arrays of key-value pairs is a common task. Suppose you have an object like this:

{
  "1": 5,
  "2": 7,
  "3": 0,
  "4": 0,
  "5": 0,
  "6": 0,
  "7": 0,
  "8": 0,
  "9": 0,
  "10": 0,
  "11": 0,
  "12": 0
}
Copy after login

And you want to transform it into an array like this:

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

Here's how to achieve this conversion using JavaScript's built-in functions:

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]]);
Copy after login

In this solution, we first use the Object.keys() method to obtain an array of the object's keys (["1", "2", "3", ...]). Then, we utilize the map() method to create a new array. The map() function takes each key as a parameter, wraps it in an array ([key]), and appends the corresponding value from the original object (obj[key]), resulting in an array of key-value pairs ([["1", 5], ["2", 7], ["3", 0], ...]).

The above is the detailed content of How Can I 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template