Loading string format arrays into an array - javascript

I am getting a set of Arrays in string format from Database like
["#464b4e","#7ebcbd"], ["#747493","#f5f6f7"], ["#58383c","#8d8566"]
Now I need to load them into array to make an array of arrays. Using this code
let imgIndicators = [];
imgIndicators.push( obj[i]['dicatorsbg']);
console.log(imgIndicators);
is creating an array like
["["#464b4e","#7ebcbd"], ["#747493","#f5f6f7"], ["#58383c","#8d8566"]"]
which as you can see is big long string item, so I tried splitting the data by , like
imgIndicators.push( obj[i]['dicatorsbg'].split(','));
This time code is accepting all , and creating an array of 6 string elemet like
["["#464b4e"", ""#7ebcbd"]", " ["#747493"", ""#f5f6f7"]", " ["#58383c"", ""#8d8566"]"]
How can I fix this code to create something like this?
[
["#464b4e", "#7ebcbd"],
["#747493", "#f5f6f7"],
["#58383c", "#8d8566"]
]

If you are really sure that the format will be correct, you can try:
imgIndicators = JSON.parse("[" + obj[i]['dicatorsbg'] + "]");

Its easy , You have to use JSON.parse() as shown below, shall give you your required result.
//your db output string
var yourStringArray = '["#464b4e","#7ebcbd"], ["#747493","#f5f6f7"], ["#58383c","#8d8566"]' ;
// the array you want
var requiredArray = JSON.parse("[" + yourStringArray + "]");
More solutions can be found on this thread issue : Elegant way to convert string of Array of Arrays into a Javascript array of arrays

Related

Conversion of string to list from a file

I have a file in which the data(list) looks something like this
[5,[5,[5,100,-200],200,-400],300,-500]
Now when I read this file in an angular application, the file contents would be converted to string and hence would return a string object which would look something like this
"[5,[5,[5,100,-200],200,-400],300,-500]"
Is there a way where I can convert this back to the list in which it was originally present?
There is one approach but the solution is for a different problem. If my file has data
200
300
400
500
Then I can split this string by using
var newData = fileContent.split('\n');
desiredList = []
for(var z=0;z<newData.length;z++){
desiredList.push(parseInt(newData[z]))
}
The desired list would give me a list which I wanted. But for the question which I asked is there any approach?
JSON.parse("[5,[5,[5,100,-200],200,-400],300,-500]") should convert it to JavaScript object.
You can use eval()
var str = "[5,[5,[5,100,-200],200,-400],300,-500]";
var jsonArr = eval(str);
console.log(jsonArr);

Adding an Individual JSON Object to an Array to Parse and Process

I have the following json object samples, i.e.:
{"id":"value1" , "time":"valuetime1"}
{"id":"value2" , "time":"valuetime2"}
{"id":"value3" , "time":"valuetime3"}
{"id":"value4" , "time":"valuetime4"}
{"id":"value5" , "time":"valuetime5"}
{"id":"value6" , "time":"valuetime6"}
{"id":"value7" , "time":"valuetime7"}
{"id":"value8" , "time":"valuetime8"}
Based on the above, I would like to add all these json objects to an array, where I can then process and access the array for each json object and extract id1 value together with time1 value and so forth.
I believe I have to use JSON.parse but unsure of how to firstly add these objects to an array and then be able to also parse and access each object's data.
Think of each row above as a separate JSON object which I would like added to an array that is parsed.
Read the file line by line (each line is a separate json)
Parse the line json text to JavaScript object
Put/push/append JavaScript object into a JavaScript array
This is not valid JSON, so JSON.parse would not work, but assuming you have the text in a string variable, you can convert it to JSON with something like:
data = "[" + data.replace(/\}/g, "},").replace(/,$/,"") + "]";
and then parse it.
UPDATE:
var array = [];
// for each input line
var obj = JSON.parse(line);
array.push(obj);
var id = obj.id;
var time = obj.time;
...
Appreciate the responses but I believe I have managed to solve my own question.
Furthermore, as #Mr. White mentioned above, I did have my property names in error which I have now sorted - thanks.
Using the data above, all I was after was the following:
UPDATED
var s = '{"id":"value1","time":"valuetime1"},{"id":"value2","time":"valuetime2"},{"id":"value3","time":"valuetime3"},{"id":"value4","time":"valuetime4"},{"id":"value5","time":"valuetime5"}, {"id":"value6","time":"valuetime6"},{"id":"value7","time":"valuetime7"},{"id":"value8","time":"valuetime8"}';
var a = JSON.parse('[' + s + ']');
a.forEach(function(item,i){
console.log(item.id + ' - '+ item.time);
});
Thanks for the heads up #torazaburo - have updated my answer which I should've done much earlier.

How to convert a string to JSON format?

I was getting list in array form. So at first place i converted array list to string-
var myJsonString = JSON.stringify(result);
myJsonString="[{"productId":"PI_NAME",
"firstName":null,
"lastName":null,
"customer":null
},
{"productId":"PI_NAME",
"firstName":null,
"lastName":null,
"customer":null
}]"
But again i need to convert myJsonString to Json format, What i need to do? I mean i need to replace 1st" and last ", I guess
You need to call parse now.
JSON.parse(myJsonString)
First, if you ever find yourself building a JSON string by concatenating strings, know that this is probably the wrong approach.
I don't really understand how the first line of your code relates to the second, in that you are not doing anything with JSON-encoded string output from result, but instead just overwriting this on the following line.
So, I am going to limit my answer to show how you could better form JSON from an object/array definition like you have. That might look like this:
// build data structure first
// in this example we are using javascript array and object literal notation.
var objArray = [
{
"productId":"PI_NAME",
"firstName":null,
"lastName":null,
"customer":null
},{
"productId":"PI_NAME",
"firstName":null,
"lastName":null,
"customer":null
}
];
// now that your data structure is built, encoded it to JSON
var JsonString = JSON.stringify(objArray);
Now if you want to work with JSON-encoded data, You just do the opposite:
var newObjArray = JSON.parse(JsonString);
These are really the only two commands you should ever use in javascript when encoding/decoding JSON. You should not try to manually build or modify JSON strings, unless you have a very specific reason to do so.

How to change data type in an array

I have an array obtained from a database that looks like this:
array1 = [Hello, Bye];
And not as I'd want:
array1 = ["Hello", "Bye"];
And so the compiler tells me that Hello and Bye are not defined. Is there any way of changing it without the need of changing the method to obtain it? It is a bit complex and I'd prefer editing it in the html file rather than changing the whole system. I've tried with String(array1) but it does not work. Any ideas? Thanks!
If i understand correctry, wrap your array variable as string with " or '
var string = "[Hello, Bye]";
string = string.replace(/(^\[)|(\]$)|(\s+)/g, '');
var array = string.split(',');
console.log(array);

Converting a string to a multi-dimensional array

I have a nested for loop that creates a empty string value that represents a multidimensional array. Once the for loops have finished the result is something like this:
"[[0,0,0,0],[0,0,0,0]]"
I would like to add this to a multidimensional array within my code, how would i do this?
I have tried:
map = eval("[[0,0,0,0],[0,0,0,0]]");
but this does not produce the correct multidimensional array i am looking for.
I am looking to be able to use the array like this:
map[0][1] == 1;
Thanks
You could parse the string using JSON.parse() (MDN docu).
var str = "[[0,0,0,0],[0,0,0,0]]";
var map = JSON.parse( str );
However, in your example there is no entry equaling 1, so you requirement map[0][1] == 1 wont be fulfilled that way.

Categories

Resources