Open In App

How to Convert String of Objects to Array in JavaScript ?

Last Updated : 12 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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":"xys@geeksforgeeks.org"}]';
let arr = JSON.parse(str);

console.log(arr);

Output
[
  { company: 'Geeks', contact: '+91-9876543210' },
  { address: 'sector 136', mail: 'xys@geeksforgeeks.org' }
]


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":"xys@geeksforgeeks.org"}]';

let arr = eval(str);

console.log(arr);

Output
[
  { company: 'Geeks', contact: '+91-9876543210' },
  { address: 'sector 136', mail: 'xys@geeksforgeeks.org' }
]


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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads