String to JavaScript Array - javascript

My Ajax call gets "[['Best Value (62)',62 ],['LPTA (32)',32 ],] " as the return value. I need to pass this as an array. Is there a way to make the string into an array without resorting to eval()?

If you get rid of the trailing comma and change the double quotes to escaped double quotes and anything else you have in the array is well formed then you can use JSON.parse to turn the string into an array. If you have access to the serverside code you'll likely want to make the changes there rather than in your js.
JSON.parse("[[\"Best Value (62)\",62],[\"LPTA (32)\",32]]")

JSON.parse("[['Best Value (62)',62 ],['LPTA (32)',32 ],]".replace(/(,])$/, ']').replace(/'/g, '"'))

What you have isn't JSON, but is valid JavaScript (assuming the extra comma was a copy-paste error). And, as much as I dislike it, you can use eval:
// convert the input in to a javascript array
var o = eval("[['Best Value (62)',62],['LPTA (32)',32]]");
// use jQuery map to grab only the first array value and return
// each selection back as an array
$.map(o, function(a){
return a[0];
}); // ['Best Value (62)','LPTA (32)'];
if the extra comma is there to stay, you can use a little more processing to get rid of it:
var data = "[['Best Value (62)',62],['LPTA (32)',32],]";
var o = eval(data.replace(/\],\]$/,']]'));
$.map(o, function(a){
return a[0];
});

Related

how can i get returned value with double quotes in javascript

i want to get a variable value with double quoted in javascript. i have an input field. i get the value from there but it is single quoted.
i try the below code already
let id=document.querySelector("#v_id"); //v_id is input field ID
let stringID= id.value;
var vObj = {id:stringID};
result is like that { id: '1'} see single quoted
i cannot use this value in JSON object.
i need a result like { id: "1"} see double quoted
i am expecting your precious answer
Use JSON.stringify
console.log(JSON.stringify('123123'))
You actually don't need to convert it. Rather you can use bracket notation while creating the key
jsonObj[id.value] = 'someValue';

HashMap example in pure JavaScript

I have String like below.
10=150~Jude|120~John|100~Paul#20=150~Jude|440~Niroshan#15=111~Eminem|2123~Sarah
I need a way to retrieve the string by giving the ID.
E.g.: I give 20; return 150~Jude|440~Niroshan.
I think I need a HashMap to achieve this.
Key > 20
Value > 150~Jude|440~Niroshan
I am looking for an pure JavaScript approach. Any Help greatly appreciated.
If you're getting the above string in response from server, it'll be better if you can get it in the below object format in the JSON format. If you don't have control on how you're getting response you can use string and array methods to convert the string to object.
Creating an object is better choice in your case.
Split the string by # symbol
Loop over all the substrings from splitted array
In each iteration, again split the string by = symbol to get the key and value
Add key-value pair in the object
To get the value from object using key use array subscript notation e.g. myObj[name]
var str = '10=150~Jude|120~John|100~Paul#20=150~Jude|440~Niroshan#15=111~Eminem|2123~Sarah';
var hashMap = {}; // Declare empty object
// Split by # symbol and iterate over each item from array
str.split('#').forEach(function(e) {
var arr = e.split('=');
hashMap[arr[0]] = arr[1]; // Add key value in the object
});
console.log(hashMap);
document.write(hashMap[20]); // To access the value using key
If you have access to ES6 features, you might consider using Map built-in object, which will give you helpful methods to retrieve/set/... entries (etc.) out-of-the-box.

producing a word from a string in javascript

I have a string which is name=noazet difficulty=easy and I want to produce the two words noazet and easy. How can I do this in JavaScript?
I tried var s = word.split("=");
but it doesn't give me what I want .
In this case, you can do it with that split:
var s = "name=noazet difficulty=easy";
var arr = s.split('=');
var name = arr[0]; //= "name"
var easy = arr[2]; //= "easy"
here, s.split('=') returns an array:
["name","noazet difficulty","easy"]
you can try following code:
word.split(' ').map(function(part){return part.split('=')[1];});
it will return an array of two elements, first of which is name ("noazet") and second is difficulty ("easy"):
["noazet", "easy"]
word.split("=") will give you an array of strings which are created by cutting the input along the "=" character, in your case:
results = [name,noazet,difficulty,easy]
if you want to access noazet and easy, these are indices 1 and 3, ie.
results[1] //which is "noazet"
(EDIT: if you have a space in your input, as it just appeared in your edit, then you need to split by an empty string first - " ")
Based on your data structure, I'd expect the desired data to be always available in the odd numbered indices - but first of all I'd advise using a different data representation. Where is this string word coming from, user input?
Just as an aside, a better idea than making an array out of your input might be to map it into an object. For example:
var s = "name=noazet difficulty=easy";
var obj = s.split(" ").reduce(function(c,n) {
var a = n.split("=");
c[a[0]] = a[1];
return c;
}, {});
This will give you an object that looks like this:
{
name: "noazert",
difficulty: "easy"
}
Which makes getting the right values really easy:
var difficulty = obj.difficulty; // or obj["difficulty"];
And this is more robust since you don't need to hard code array indexes or worry about what happens if you set an input string where the keys are reversed, for example:
var s = "difficulty=easy name=noazet";
Will produce an equivalent object, but would break your code if you hard coded array indexes.
You may be able to get away with splitting it twice: first on spaces, then on equals signs. This would be one way to do that:
function parsePairs(s) {
return s.split(' ').reduce(
function (dict, pair) {
var parts = pair.split('=');
dict[parts[0]] = parts.slice(1).join('=');
return dict;
},
{}
);
}
This gets you an object with keys equal to the first part of each pair (before the =), and values equal to the second part of each pair (after the =). If a string has multiple equal signs, only the first one is used to obtain the key; the rest become part of the value. For your example, it returns {"name":"noazet", "difficulty":"hard"}. From there, getting the values is easy.
The magic happens in the Array.prototype.reduce callback. We've used String.prototype.split to get each name=value pair already, so we split that on equal signs. The first string from the split becomes the key, and then we join the rest of the parts with an = sign. That way, everything after the first = gets included in the value; if we didn't do that, then an = in the value would get cut off, as would everything after it.
Depending on the browsers you need to support, you may have to polyfill Array.prototype.reduce, but polyfills for that are everywhere.

Sending an array with JavaScript to the next page

The combination of my methods of declaring an array, adding elements to the array and applying the method toString() does not work. Essentially I enter a certain number (between one and five) values to textvariables : fontVorto1, fontVorto2, fontVorto3 ……… in the html-part of the document.
When I decide on leaving the remaining textelements empty, I click on a button, to assign them to an array, by way of the following function:
function difinNombroFv () {
var fontVortoj = new array();
fontVortoj[0] = document.getElementsByName("fontVorto1")[0].value;
fontVortoj[1] = document.getElementsByName("fontVorto2")[0].value;
fontVortoj[2] = document.getElementsByName("fontVorto3")[0].value;
……………….
and put them together in a string:
x = fontVortoj.toString();
document.getElementsByName("fontVorto")[0].value = x;
(the extra variable x is not needed) to enable me sending them to the next document, where I want to unserialize them with
$fontVortoj = unserialize($_POST["fontVorto"]);
I tested the method toString() by insering an alert(x), but the result was that I got for x the value of "fontVorto1" only.
I met solutions with JSON, jQuery etc., but I never used those "languages", only HTML, JavaScript, PHP.
Will my Christmas day be spoiled because of this simple problem ;>)?
couple of things to note:
1. var fontVortoj = new array(); . here new array() is not correct. it should be:
var fontVortoj = new Array();
now if you call fontVortoj.toString(), then it will convert the array and return a string with array elements separated by comma.
you can rebuild the array from the string in php by using "explode" function.
you can rebuild the array from the string in javascript by using "split" function.
Apparently I misunderstood the question to begin with.
To serialize an astray, you can use .join()
By default, it will give you the values, joined by commas.
To deserialize, use .split()
If there's a chance that there might be commas in your values, choose a more elaborate string for joining:
var ar = ["a", "b"];
var serialized = ar.join("|"); // "a|b"
var deserialized = serialized.split("|"); //["a", "b"]
The string that you use for joining and splitting can be as long as you like.
If you want to be completely covered against any values, then you need to look at JSON.stringify() & JSON.parse(). But that had browser compatibility issues.

Robust String Split

I have a JavaScript function:
function doSomething(arg) {
var array = arg.split(',');
// etc...
}
arg is populated using jQuery's .data('myId') function.
Often, myId contains a comma separated list of integers and the code works great. However, if myId only contains a single integer, the code fails with the error
Object doesn't support property or method 'split'
Is there a compact, robust method to create the array without including if statements to handle the boundary conditions of one integer or an empty string?
attr will return a string, while data will try to parse the value and return an object with the "correct" type.
foo.attr('data-myId'); //pass this instead
You can't get around identifying an empty string without an if though. You either need to check for it, or for an array with a single empty string element.
You have two unrelated problems.
The first one is for case of empty string: Split will return a one-element array with an empty string. Just check for it and compensate.
var array;
if (arg == "") array = [];
If there is a single integer, I believe you are not getting a string from the .data(), but an actual integer; so first convert it into a string:
else array = String(arg).split(',');
Alternately, you could just avoid the jQuery magic, and access the attribute directly - all data() attributes are just attributes with data- prefixed.
.data will try to guess the type of the value based on its contents, so it becomes a number. You could use .attr, which always returns a string if it's available as an attribute. Alternatively, cast to a string:
('' + arg).split(',')
//or
String(arg).split(',')
I'm actually not sure whether one is preferred or not.
Also note that ''.split(',') returns [''] or an array with an empty string element. You can get around that with .filter(function (elem) { return elem !== ''; })
Another possible alternative is to use dataset on the element itself.

Categories

Resources