How to use eval() Method In Javascript
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":"Geeks", "contact":"+91-9876543210"},
{"address":"sector 136", "mail":"xys@w3wiki.org"}]';
let arr = eval(str);
console.log(arr);
Output
[ { company: 'Geeks', contact: '+91-9876543210' }, { address: 'sector 136', mail: 'xys@w3wiki.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.
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