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:
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);
Output:
[[1,5], [2,7], [3,0], [4,0]...]
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!