4

There is array (in JavaScript) of items written in the following way:

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

There is a string variable that contains string representation of next item:

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

How can I convert string into a new "item" that can be pushed into 'arr' array?

2 Answers 2

2

You're looking for $.parseJSON.

Sign up to request clarification or add additional context in comments.

1 Comment

That will work if OP modifies the string to make it valid JSON.
0

You can either eval the string if it's safe (not user input):

arr.push(eval(s));

Or, strip the first and last characters of the string, and then split it by the comma (provided there are no commas within the array values themselves):

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

3 Comments

.eval() would work. The .split() method sort of works, but wouldn't give the actual values that I'm guessing OP wants. They'll all be Strings, some with extra spaces, some with single quotes inside. ["6"," 7"," 'new'"," 8"," 'something'"]
It is not a user input. Thank you!
@patrick - you're right about the split. Moment of carelessness and it completely didn't occur to me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.