How to Convert String of Objects to Array in JavaScript ?
Last Updated :
30 Aug, 2024
This article will show you how to convert a string of objects to an array in JavaScript. You have a string representing objects, and you need to convert it into an actual array of objects for further processing. This is a common scenario when dealing with JSON data received from a server or stored in a file.
Using JSON.parse() Method
The most common and straightforward way to convert a string of objects to an array of objects is by using JSON.parse() method. This method parses a JSON string into a JavaScript object or array.
Example: This example shows the use of the above-mentioned approach.
JavaScript
let str = '[{"company":"Geeks", "contact":"+91-9876543210"},
{"address":"sector 136", "mail":"[email protected]"}]';
let arr = JSON.parse(str);
console.log(arr);
Output[
{ company: 'Geeks', contact: '+91-9876543210' },
{ address: 'sector 136', mail: '[email protected]' }
]
Using eval() Method
Another approach to convert a string of objects to an array is by using the eval() function. However, this method is generally not recommended due to security risks associated with executing arbitrary code.
Example: This example shows the use of the above-explained approach.
JavaScript
let str = '[{"company":"Geeks", "contact":"+91-9876543210"},
{"address":"sector 136", "mail":"[email protected]"}]';
let arr = eval(str);
console.log(arr);
Output[
{ company: 'Geeks', contact: '+91-9876543210' },
{ address: 'sector 136', mail: '[email protected]' }
]
Using the Function Constructor
Another method to convert a string of objects to an array of objects is by using the Function constructor. This method is safer than eval() as it creates a new function and doesn't have access to the local scope.
Example: This example shows the use of the Function constructor to convert a string of objects to an array of objects.
JavaScript
let str = '[{"company":"Geeks", "contact":"+91-9876543210"}, {"address":"sector 136", "mail":"[email protected]"}]';
let arr = (new Function('return ' + str))();
console.log(arr);
Output[
{ company: 'Geeks', contact: '+91-9876543210' },
{ address: 'sector 136', mail: '[email protected]' }
]
By Spliting JSON into Components
This method splits the JSON string into components and reconstructs the objects. It is a more manual approach and assumes that the JSON string is well-formed and simple.
Example:
JavaScript
function parseStringToArrayOfObjects(str) {
// Remove surrounding brackets and extra spaces
str = str.trim().slice(1, -1).trim();
const objectStrings = str.split(/(?<=\}),\s*(?=\{)/);
let result = [];
function parseObjectString(objectStr) {
// Remove leading and trailing spaces and curly braces
objectStr = objectStr.trim().slice(1, -1).trim();
// Initialize the object
let obj = {};
let key = '';
let value = '';
let inKey = true;
let inString = false;
let isEscaped = false;
for (let i = 0; i < objectStr.length; i++) {
let char = objectStr[i];
if (char === '\\') {
// Handle escaped characters
isEscaped = !isEscaped;
value += char;
continue;
}
if (char === '"' && !isEscaped) {
inString = !inString;
if (!inString) {
if (inKey) {
key = value;
} else {
obj[key] = value;
}
value = '';
inKey = !inKey;
}
continue;
}
if (inString) {
value += char;
} else if (char === ':') {
inKey = false;
} else if (char === ',') {
if (!inKey) {
obj[key] = value;
value = '';
inKey = true;
}
} else if (char === ' ' || char === '\n' || char === '\t') {
// Ignore whitespace
continue;
} else {
value += char;
}
isEscaped = false;
}
if (key && !inKey) {
obj[key] = value;
}
return obj;
}
// Parse each object string and add it to the result array
for (let objectStr of objectStrings) {
result.push(parseObjectString(objectStr));
}
return result;
}
const str = '[{"company":"Geeks", "contact":"+91-9876543210"}, {"address":"sector 136", "mail":"[email protected]"}]';
const arr = parseStringToArrayOfObjects(str);
console.log(arr);
Output[
{ company: 'Geeks', contact: '+91-9876543210' },
{ address: 'sector 136', mail: '[email protected]' }
]
Similar Reads
How to Convert String to Array of Objects JavaScript ? Given a string, the task is to convert the given string to an array of objects using JavaScript. It is a common task, especially when working with JSON data received from a server or API. Below are the methods that allow us to convert string to an array of objects:Table of ContentUsing JSON.parse()
4 min read
How to Convert Object to Array in JavaScript? In this article, we will learn how to convert an Object to an Array in JavaScript. Given an object, the task is to convert an object to an Array in JavaScript. Objects and Arrays are two fundamental data structures. Sometimes, it's necessary to convert an object to an array for various reasons, such
4 min read
How to convert a map to array of objects in JavaScript? A map in JavaScript is a set of unique key and value pairs that can hold multiple values with only a single occurrence. Sometimes, you may be required to convert a map into an array of objects that contains the key-value pairs of the map as the values of the object keys. Let us discuss some methods
6 min read
How to Convert an Array of Objects to Map in JavaScript? Here are the different methods to convert an array of objects into a Map in JavaScript1. Using new Map() ConstructorThe Map constructor can directly create a Map from an array of key-value pairs. If each object in the array has a specific key-value structure, you can map it accordingly.JavaScriptcon
3 min read
How to Convert JSON to string in JavaScript ? In this article, we are going to learn the conversion of JSON to string in JavaScript. Converting JSON to a string in JavaScript means serializing a JavaScript object or data structure represented in JSON format into a textual JSON string for data storage or transmission.Several methods can be used
3 min read
How to Convert String to JSON in JavaScript? In JavaScript, converting a string to JSON is important for handling data interchangeably between server and client, parsing external API responses, and storing structured data in applications. Below are the approaches to converting string to JSON in JavaScript: Table of Content Using JSON.parse()Us
2 min read
How to Convert a Map to JSON String in JavaScript ? A Map is a collection of key-value pairs, where each key is unique. In this article, we will see how to convert a Map to a JSON (JavaScript Object Notation) string in JavaScript. However, JSON.stringify() does not directly support Map objects. Table of ContentUsing Object.fromEntries() MethodUsing A
2 min read
Convert JSON String to Array of JSON Objects in JavaScript Converting a JSON string to an array of JSON objects in JavaScript involves transforming a structured text format (JSON) into a usable JavaScript array. This allows developers to work directly with the data, enabling easier manipulation, analysis, and display of information.1. Using JSON.parse() Met
2 min read
How to convert array of strings to array of numbers in JavaScript ? Converting an array of strings to an array of numbers in JavaScript involves transforming each string element into a numerical value. This process ensures that string representations of numbers become usable for mathematical operations, improving data handling and computational accuracy in applicati
4 min read
How To Convert Base64 to JSON String in JavaScript? There could be situations in web applications, where there is a need to decode the data from Base64 format back into its original JSON format. It generally happens when one has to transmit data over the network where Base64 encoding is well suited for encoding binary data.In this article, we will se
2 min read