How to Convert String of Objects to Array in JavaScript ?
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.
Table of Content
- Using JSON.parse() Method
- Using eval() Method
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.
let str = '[{"company":"Beginner", "contact":"+91-9876543210"},
{"address":"sector 136", "mail":"xys@w3wiki.net"}]';
let arr = JSON.parse(str);
console.log(arr);
Output
[ { company: 'Beginner', contact: '+91-9876543210' }, { address: 'sector 136', mail: 'xys@w3wiki.net' } ]
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.
let str = '[{"company":"Beginner", "contact":"+91-9876543210"},
{"address":"sector 136", "mail":"xys@w3wiki.net"}]';
let arr = eval(str);
console.log(arr);
Output
[ { company: 'Beginner', contact: '+91-9876543210' }, { address: 'sector 136', mail: 'xys@w3wiki.net' } ]
While eval() can parse the string and create an array of objects, it should be used with caution and only when the source of the string is trusted.