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.
javascriptlet 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.
javascriptlet 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.
javascriptlet 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.
javascriptlet 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.