Home > Software engineering >  Is there a way to convert a string to a proper array, not an array of strings or an array of charact
Is there a way to convert a string to a proper array, not an array of strings or an array of charact

Time:03-20

I have this string “[{value: 1400, value1: 50, value2: 48}, {value: 1500, value1: 20, value2: 88}]" and I need to convert into a list [{value: 1400, value1: 50, value2: 48}, {value: 1500, value1: 20, value2: 88}] in JavaScript, is there a way to do that??

CodePudding user response:

you can use the eval() function. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_eval!)

Please be aware, that eval() shouldnt be used generally as you can read in the article above.

Example:

const array = eval('[{value: 1400, value1: 50, value2: 48}, {value: 1500, value1: 20, value2: 88}]');

Edit: I would suggest to modify you string to fit the JSON-Standard. To achieve this, you would have to put the keys of your objects in quotation marks like this:

let yourString =  '[{"value": 1400, "value1": 50, "value2": 48}, {"value": 1500, "value1": 20, "value2": 88}]';
const array = JSON.parse(`${yourString}`);

This will work ^^

  • Related