JavaScript - jQuery: how to create an array element based on a string

There is an array (in JavaScript) of elements written as follows:

var arr = [ 
    [1, 2, 'abc', 3, 'cab'],
    [3, 4, 'def', 5, 'ghi'],
    ];

There is a string variable that contains a string representation of the following element:

var s = "[6, 7, 'new', 8, 'something']";

How can I convert a string to a new "element" that can be placed in an arr array?

+4
source share
2 answers

You can either evalstring if it is safe (not user input):

arr.push(eval(s));

Or, separate the first and last characters of the string, and then separate it with a comma (assuming there are no commas inside the array values ​​themselves):

arr.push(s.substring(1, s.length - 1).split(","));
0
source

You are looking for $.parseJSON.

+2

Source: https://habr.com/ru/post/1781935/


All Articles