乐闻世界logo
搜索文章和话题

How to convert JSON object to JavaScript array?

1个答案

1

To convert a JSON object to a JavaScript array, we need to understand that a JSON object is a text-based representation of a data structure, typically used to represent collections of key-value pairs, whereas a JavaScript array is a data structure capable of holding multiple values.

The typical format of a JSON object is as follows:

json
{ "key1": "value1", "key2": "value2", "key3": "value3" }

To convert such a JSON object to a JavaScript array, we have several methods depending on the desired array format.

Example 1: Convert JSON Object Values to an Array

If we only want to extract the values from the JSON object, we can use the Object.values() method.

javascript
let jsonObject = { "key1": "value1", "key2": "value2", "key3": "value3" }; let valuesArray = Object.values(jsonObject); console.log(valuesArray); // Output: ["value1", "value2", "value3"]

Example 2: Convert JSON Object Keys to an Array

If we want to extract the keys, we can use the Object.keys() method.

javascript
let keysArray = Object.keys(jsonObject); console.log(keysArray); // Output: ["key1", "key2", "key3"]

Example 3: Convert JSON Object Key-Value Pairs to an Array

If we want to obtain both keys and values as an array of arrays, we can use the Object.entries() method.

javascript
let entriesArray = Object.entries(jsonObject); console.log(entriesArray); // Output: [["key1", "value1"], ["key2", "value2"], ["key3", "value3"]]

Example 4: Parse JSON String to Object and Convert to Array

Sometimes we receive a JSON-formatted string instead of a JSON object. In this case, we need to first use JSON.parse() to parse the JSON string into a JavaScript object, and then use one of the above methods to convert it to an array.

javascript
let jsonString = '{"key1":"value1","key2":"value2","key3":"value3"}'; // Parse the JSON string into a JSON object let parsedJsonObject = JSON.parse(jsonString); // Convert the object's values to an array let valuesArray = Object.values(parsedJsonObject); console.log(valuesArray); // Output: ["value1", "value2", "value3"]

These are several methods to convert a JSON object to a JavaScript array, and the choice depends on the desired output format.

2024年6月29日 12:07 回复

你的答案