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 }
And you want to transform it into an array like this:
[ [1, 5], [2, 7], [3, 0], [4, 0], ... ]
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]]);
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!