Converting int array in string format to array - javascript

I have an array of integers stored in string format.
eg:
"[3,2,1]"
How can I convert this to an actual array?
I've searched high and low for a simple solution but I can't seem to find it.
Passing the string into JSON.parse and $.parseJSON results in "[" being shown for the 0 index. So I'm assuming it's not doing anything.

var arr = JSON.parse("[3,2,1]")

var text = "[3,2,1]";
var obj = JSON.parse(text);
console.log(obj);

You could use jQuery $.parseJSON() method :
var arr = $.parseJSON("[3,2,1]");
var str = "[3,2,1]";
console.log( $.parseJSON(str) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Or pure javascript method JSON.parse() :
var arr = JSON.parse("[3,2,1]");
Hope this helps.
var str = "[3,2,1]";
console.log( JSON.parse("[3,2,1]") );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

So I've figured out I needed to slice the first and last characters off as for some reason the string was being returned as ""[3,2,1]"" rather than "[3,2,1]" even though it's stored without quotes.

From your updated description it appears you have a string that starts and ends with ", so a simple JSON.parse will not work, since that will just convert what's between the "'s to a string. You need to either JSON.parse twice, since you have an array of integers embedded in a string, or manually parse.
JSON.parse twice way:
var str = '"[3,2,1]"';
var parsedStr = JSON.parse(str); // results in a string with contents [3,2,1]
var intArray = JSON.parse(parsedStr); // results in an int array with contents [3,2,1]
Or, if format could change to be non-JSON at some point, manual way:
var str = '"[3,2,1]"';
var intArray = [];
str.substr(2,str.length-3).split(/,/g).forEach(function(numStr) {
intArray.push(parseInt(numStr));
});

Related

Alternative eval() to execute the string

My array is A=['Apple','Peach','Orange']in Javascript, someone pass me the string like "A[1]" , how to convert the string "A[1]" to an executable item, so I can get 'Peach' as the result.
eval(A[1]) used to work but is not allowed here.
Using regex you can parse out the variable and the index, then grab them off the window object.
A=['Apple','Peach','Orange'];
let string = "A[1]";
let variable = string.match(/[^[]*/)[0];
let index = string.match(/\[(.*)\]/)[1];
console.log(window[variable][index]);
You could split by apostrophe and then filter out the odd array members:
var arrayString = "A=['Apple','Peach','Orange']"
var parsed = arrayString.split("'").filter(function(a, b){return b % 2});
console.log(parsed)

How to convert array defined in string variable with \r\n using Javascript?

I have a string variable with array data .
var str = "[\r\n  10,\r\n  20\r\n]" ;
I want to convert above string to array like using javascript .
Output :-
var arr = [10,20];
You can simply use JSON.parse - it will ignore the newlines and convert the string representation of an array to a JavaScript array:
var str = "[\r\n 10,\r\n 20\r\n]" ;
var arr = JSON.parse(str);
console.log(Array.isArray(arr))
console.log(arr)
You need only to parse that string as a JSON, because it is clearly an array.
So this is the procedure:
var str = "[\r\n 10,\r\n 20\r\n]";
const myArray = JSON.parse(str);
console.log(myArray);
UPDATE:
If you are wondering why those special chars (\r\n) are going away:
// a string
const str = "[\r\n 10,\r\n 20\r\n]";
// if I print out this, Javascript, will automatically replace those special
// chars with what they means (new line)
console.log(str);
console.log(typeof(str));
// so if we are going to parse our string to the JSON parser
// it will automatically transform the special chars to new lines
// and then convert the result string "[10,20]" to an array.
const myArray = JSON.parse(str);
console.log(myArray);
console.log(typeof(myArray));

How convert a string representation of date array to array JS?

I need to convert a string representation of array to JS array for looping purpose
the string is single quoted
in My js
var length1 = $('.length').text(); //['2018-9-24', '2018-9-26', '2018-9-25']
console.log(length1.length) // 39 as output i need it as 3
to loop through each date
Any help would be appreciated
I tried
var myArray=json.parse(length1) // but its not working
Replace single quotes with double and then parse it:
var str = "['2018-9-24', '2018-9-26', '2018-9-25']";
console.log(JSON.parse(str.replace(/'/g, '"')));
I had done this in an another way
var objectstring = "['2018-9-24', '2018-9-26', '2018-9-25']";
var objectStringArray = (new Function("return [" + objectstring+ "];")());

Convert string (looking like array) to multidimensional array

I have a string:
[[-3.9,-160.1,34.7],[-0.4,16.3,18.0],[236,236,231],'SMTH 123',35]
How I can convert it to a multidimensional array?
You can use JSON.parse() to convert a string into an object, assuming it's valid JSON to begin with. Your data has strings delimited by single quotes, which is not valid JSON. If you replace them with double quotes then it will work...
var s = "[[-3.9,-160.1,34.7],[-0.4,16.3,18.0],[236,236,231],'SMTH 123',35]";
var ar = JSON.parse(s.split("'").join("\""));
console.log(ar);
How about doing something like this:
function stringToObject(data) {
var converted = {};
try {
converted = JSON.parse(data);
} catch(err) {
console.log('Provided data is not valid', err);
}
return converted;
}
console.log(stringToObject('[[-3.9,-160.1,34.7],[-0.4,16.3,18.0],[236,236,231],"SMTH 123",35]'));
console.log(stringToObject('[[-3.9,-160.1,34.7],[-0.4,16.3,18.0],[236,236,231')); // invalid string
Notice that I have changed ' into " in my sample if that is a problem you may take a look at conversion done in another answer for that question.
Assuming JQuery is also okay:
var arr = $.parseJSON('[[-3.9,-160.1,34.7],[-0.4,16.3,18.0],[236,236,231],'SMTH 123',35]')

How to Convert Array-like String to Array

I have a string that looks like an array: "[918,919]". I would like to convert it to an array, is there an easier way to do this than to split and check if it is a number? Thanks
Use JSON.parse.
var myArray = JSON.parse("[918,919]");
You can get rid of the brackets at the beginning and the end, then use:
str.split(",")
which will return an array split by the comma character.
EDIT
var temp = new Array();
temp = "[918,919]".slice( 1, -1).split(",");
for (a in temp ) {
temp[a] = parseInt(temp[a]);
}
If you use JSON.parse the string must have " and not ' otherwise the code will fail.
for example:
let my_safe_string = "['foo','bar',123]";
let myArray = JSON.parse(my_safe_string)
the code will fail with
Uncaught SyntaxError: Unexpected token ' in JSON at position 1
instead if you use " all will work
let my_safe_string = "["foo","bar",123]";
let myArray = JSON.parse(my_safe_string);
so you have two possibility to cast string array like to array:
Replace ' with " my_safe_string.replace("'",'"'); and after do JSON.parse
If you are extremely sure that your string contain only string array you can use eval:
example:
let myArray = eval(my_safe_string );

Categories

Resources