Loading string to array of array - javascript

I am getting a set of arrays in string format which looks like
[49,16,135],[51,16,140],[50,18,150]
Now I need to save them in an array of arrays. I tried it like
let array = [];
let str = '[49,16,135],[51,16,140],[50,18,150]';
array = str.split('[]');
console.log(array);
but it is creating only one array including all string as an element while I need to have
array = [[49,16,135],[51,16,140],[50,18,150]]

Add array delimiters to each end of the string, then use JSON.parse:
const str = '[49,16,135],[51,16,140],[50,18,150]';
const json = '[' + str + ']';
const array = JSON.parse(json);
console.log(array);

You are splitting it incorrectly, in the example, it will only split of there is a [] in the string
You can create a valid JSON syntax and parse it instead like so,
let str = '[49,16,135],[51,16,140],[50,18,150]';
let array = JSON.parse(`[${str}]`);
console.log(array);

Another way you could achieve this is by using a Function constructor. This method allows you to "loosely" pass your array.
const strArr = "[49,16,135],[51,16,140],[50,18,150]",
arr = Function(`return [${strArr}]`)();
console.log(arr);

Related

Turn a String to an array Declaration

In JS :
I have this string ="[36.79025,3.01642],[36.71477,2.99761]";
I want it to be turned To a real Array =[[36.79025,3.01642],[36.71477,2.99761]];
Is this possible?
var string = "[36.79025,3.01642],[36.71477,2.99761]";
var arr = JSON.parse(`[${string}]`);
console.log(arr);
[[36.79025,3.01642],[36.71477,2.99761]]

splitting string into an object JavaScript

I have this String result:tie,player:paper,computer:paper
I guess you could split into arrays and make a object and parse it an object, however this does not seem to be a good approach.
How would I get this String as a object?
let string = "result:tie,player:paper,computer:paper"
For this particular string, I'd turn the string into proper JSON by surrounding the keys and values with "s, and then use JSON.parse:
const string = "result:tie,player:paper,computer:paper";
const json = '{' + string.replace(/(\w+):(\w+)/g, `"$1":"$2"`) + '}';
console.log(JSON.parse(json));
Though, ideally, whatever serves you that string should be giving you something in JSON format, rather than forcing you to resort to a hacky method like this to deal with a broken input.
Split on ,, iterate through, and split each string on : and make an object key/value property based on that. Use destructuring for simplicity:
let string = "result:tie,player:paper,computer:paper";
let obj = {};
let propsArr = string.split(",");
propsArr.forEach(s => {
var [key, value] = s.split(":");
obj[key] = value;
});
console.log(obj);
Split on the , to get key:value tokens, split those by : to get the key and value, and add them to the reduced object that collects the key value pairs.
var temp = "result:tie,player:paper,computer:paper";
var obj = temp.split(',').reduce((result, token)=>{
var [key, value] = token.split(':');
result[key] = value;
return result;
}, {});
console.log(obj);

how to get required output from json stringify array

My array look like this after use this code -:
var array=xmlhttrequest.responseText;
console.log(array);
["{\"result\":{\"isvalid\":true,\"address\":\"3EL5SKSjEzFQDBmXA5JFbsZu48vKnNSdDH\",\"scriptPubKey\":\"a9148aa3d53255b44655f82d163f37ecb68057f2edf487\",\"ismine\":false,\"iswatchonly\":false,\"isscript\":true},\"error\":null,\"id\":\"curltest\"}\n"]
I want value of isvalid , how can i get this .
That's a strange response. It's a stringified array, and that array contains a single item, which is another stringified object. Here's one option:
const responseText = String.raw`["{\"result\":{\"isvalid\":true,\"address\":\"3EL5SKSjEzFQDBmXA5JFbsZu48vKnNSdDH\",\"scriptPubKey\":\"a9148aa3d53255b44655f82d163f37ecb68057f2edf487\",\"ismine\":false,\"iswatchonly\":false,\"isscript\":true},\"error\":null,\"id\":\"curltest\"}\n"]`;
const [ stringItem ] = JSON.parse(responseText);
const itemObj = JSON.parse(stringItem);
const isvalid = itemObj.result.isvalid;
console.log(isvalid);
Note: While testing like this, you have to use String.raw so that the single backslashes are interpreted as literal backslashes and not unnecessary escape characters
The whole thing is an array as you can see it is wrapped inside [ ]. The inner content is a string, so you need to JSON.parse to convert into an object. Here is how you will get it JSON.parse(myData[0]).result.isvalid
var myData = ["{\"result\":{\"isvalid\":true,\"address\":\"3EL5SKSjEzFQDBmXA5JFbsZu48vKnNSdDH\",\"scriptPubKey\":\"a9148aa3d53255b44655f82d163f37ecb68057f2edf487\",\"ismine\":false,\"iswatchonly\":false,\"isscript\":true},\"error\":null,\"id\":\"curltest\"}\n"];
console.log("Is Valid: "+JSON.parse(myData[0]).result.isvalid);
use JSON.parse:
var obj = JSON.parse(array);
but I would try and eliminate all the unnecessary chars before using string.replace:
var json = array.replace("\", "");

Convert to String Format

I Have a string like
[ "Basic, JavaScript, PHP, Scala" ]
How to convert it like
[ 'Basic', 'JavaScript', 'PHP', 'Scala' ]
code
function loadDataToGridChiefComplaint() {
var tHRNo = document.getElementById("lblpthrno").value;
var tOPDNo = document.getElementById("lblptopd").value;
var localKeyChief = tHRNo + '-' + tOPDNo + '-ChiefComplaint';
var a = localStorage.getItem(localKeyChief);
var Item = JSON.stringify(a); // it show like ["Basic, JavaScript, PHP, Scala"]
}
JSON.stringify() returns a String so your question is incorrect. Item is not an Array.
const Item = '["Basic, JavaScript, PHP, Scala"]';
Therefore you should not use it. Instead simply return the array a in your function:
function loadDataToGridChiefComplaint() {
var tHRNo = document.getElementById("lblpthrno").value;
var tOPDNo = document.getElementById("lblptopd").value;
var localKeyChief = tHRNo + '-' + tOPDNo + '-ChiefComplaint';
return localStorage.getItem(localKeyChief); // <-- no use of JSON.stringify()
}
This way loadDataToGridChiefComplaint() is the array ["Basic, JavaScript, PHP, Scala"], it has a single element of type String that you can access with the bracket notation Item[0]:
const Item = ["Basic, JavaScript, PHP, Scala"];
console.log(Item[0]);
So in order to convert the string Item[0] into an array, use the .split method:
String.split(separator)
The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
MDN Web Docs
const Item = ["Basic, JavaScript, PHP, Scala"];
console.log(Item[0].split(', '));
If you can't modify this function you can use the opposite operation of JSON.stringify which is JSON.parse to convert the string back to an array:
const ItemString = '["Basic, JavaScript, PHP, Scala"]';
ItemArray = JSON.parse(ItemString);
And then use .split (like the previous example) to get the array of strings.
Try this :
var Item = ["Basic, JavaScript, PHP, Scala"];
// Do like this
var array = Item[0].split(', '); // Split with Comma and space(for trim whitespace)
// Or Like this
var array = Item[0].split(',').map(i => i.trim()) // Split with comma and use map to trim whitespace
console.log(array);

JavaScript string into multidimensional array

I'm passing myself a string of results from php by ajax that I would like to put into a two dimensional array in JavaScript
The string looks like: value1^*value2^*value3^*value4***value1^*value2^*value3^*value4
I would like to split the values by '^*' into the first row of the dimensional array, then the next row would be after the '***'
Desired array:
var Text = [['value1', 'value2','value3','value4'],[value1','value2','value3','value4']];
You can use split() to split your string into an array of strings ( value1^*value2^*value3^*value4 and value1^*value2^*value3^*value4 ), after that you will need map() to creates a new arrays inside each array which we get before.
Example:
var str = "value1^*value2^*value3^*value4***value1^*value2^*value3^*value4"
str = str.split('***')
str = str.map((value) => value.split('^*'))
console.log(str)
You can do something like that
var input = "value1^*value2^*value3^*value4***value5^*value6^*value7^*value8";
var res = input.split('***').map(function(rowValues){
return rowValues.split('^*');
})
console.log(res);

Categories