cannot convert string in array format such as "[55]" to array - javascript

I receive the following from another server in my payload as query param:
"[55]"
Now I want to convert it to an array in JavaScript,
Here is what I do:
var termssValidation= JSON.parse(JSON.stringify(event.termsQuery));
But when I run the following:
for(var t in termssValidation ){
console.log(termssValidation[t]);
}
I get 3 lines as follows:
[
5
5
]
How can I convert the above to an array properly?

You need just to parse the JSON string.
console.log(JSON.parse('[55]'));

JSON.stringify is excess
let j = JSON.parse("[55]")
console.log(j)

The problem is the inner JSON.stringify().
This method converts the "[66]" into ""[66]"". JSON.parse then converts this string as if the inner quotes were escaped. So the result is the original string "[66]".
Because the String in javascript is an iterable you get the individual characters as the result of the iteration.
This is the solution to your problem:
var termssValidation= JSON.parse(event.termsQuery);

This code works!
let a = "[55]";
a = JSON.parse(a);
for (let i in a) {
console.log(a[i]); //55
}

Related

A nested array of string to number

I'm looking to convert a nested array of the type string to type float, or alternatively parsing it from a text file. Format is something along the lines of this [45.68395, 32.98629],[23.6777, 43.96555],[43.66679, 78.9648]
The first step would be to create valid JSON from your string.
If your input will always follow the schema you showed us, you could just prepend and append brackets to the string. This is not a pretty solution though. You should first check if you can get valid JSON in the first place.
A solution could look like this, provided that the input string will always follow the format of "[float, float], [float, float]":
const input = "[45.68395, 32.98629],[23.6777, 43.96555],[43.66679, 78.9648]";
// Add brackets in order to have valid JSON.
const arrayString = "[" + input + "]";
// Parse the string into an object.
const parsedArray = JSON.parse(arrayString);
// Flatten the nested array to get a one dimensional array of all values.
var flattenedArrays = [].concat.apply([], parsedArray);
// Do something with your values.
flattenedArrays.forEach(floatValue => console.log(floatValue));
You can use JSON.parse, if your numbers are actually numbers in a JSON (serialized without quotes).
let test = "[[3, 4.2], [5, 6]]";
let test2 = JSON.parse(test);
console.log(test2);
Otherwise you can simply convert your array of array of strings to array of array of numbers using + and some array mapping. :
let test = [["3", "4.2"], ["5", "6"]];
let test2 = test.map((x) => x.map((y) => +y));
console.log(test2);
Of course, you can combine both solutions if for some reason you don't control the input and have a JSON containing strings.
This thread shows you how to loop through an array of strings to convert it to an array of floats.
i hope this will work..
var input = [[45.68395, 32.98629],[23.6777, 43.96555],[43.66679, 78.9648]]
var output = [];
input.forEach(o => {
o.forEach(s => parseFloat(s))
output.push(o);
})
console.log(output);

Can we iterate through json in javascript without using for..in

I have a requirement to throw a 400 Bad request error if the json payload contains duplicate keys. I am using below code to fetch all attributes in an array.
var arrayObj = [];
var attrArr = [];
var arr = {
"serviceNumer": "1612045709",
"customerRefNumber": "TCreateS9",
"customerRefNumber": "TCreateS9"
};
for (var key in arr) {
arrayObj.push(key, arr[key]);
}
console.log("arrayObj", arrayObj);
for (var i = 0; i < arrayObj.length; i = i + 2) {
attrArr.push(arrayObj[i]);
}
console.log(attrArr);
When I iterate using for..in, the duplicate keys get overridden. So please help me with any alternate approach.
JavaScript objects cannot have duplicate keys. All the keys must all be unique.
Go through the following links, this will clear your doubts StackOverflow JSObj and Finding and solving issues for duplicate keys
your JSON impementation can't handle duplicate keys,
if you take the object you've got from the JSON and convert it back to JSON, and then compare the number of colons in the string against the original. If there are duplicate keys in the original there will be fewer colons in the new JSON.
Such a check is suitable to give warning messages to noobs, but it's not bulletproof. An attacker could use escapes for colons in string values resulting in an increased count. if the requiremnt is critical you'll need to modify the JSON parser to do the check.
A JSON Object can't have duplicate Keys.
If you are getting your payload as string than you can do following:
var input = '{"serviceNumer":"1612045709","customerRefNumber":"TCreateS9","customerRefNumber":"TCreateS9"}';
if(input === JSON.stringify(JSON.parse(input)))
console.log("input has No Duplicate");
else
console.log("input has Duplicate");
here JSON.parse will convert input to JSON object and will remove duplicate keys
Hope this help you:)
you just dont know, keep do it
//you can hard code it or write it
var arr = {
"serviceNumer": "1612045709",
"customerRefNumber": "TCreateS9",
"customerRefNumber": "TCreateS93333"
};
//but when you call it it just will show the last element
console.log(arr.customerRefNumber)
/*
its like you say
var ac = 1
var ac = 3
console.log(ac)
it will show 3
*/
//make it different
var arr2 = {
"serviceNumer": "1612045709",
"customerRefNumber": "TCreateS9",
"customerRefNumber2": "TCreateS9"
};
var a = Object.getOwnPropertyNames(arr).sort()
var b = Object.getOwnPropertyNames(arr2).sort()
console.log(a)
console.log(b)

splitting json array in javascript not working

I am getting the response from ajax as json:
{"checkin_date":["2017-05-11","2017-05-18","2017-05-23","2017-05-25"]}
I need to separate these values in javascript like 2017-05-11, 2017-05-18, etc.
I tried split function in javascript but it failed. How do I achieve it?
I need the dates separately in a loop.
Parse the JSON string using JSON.parse method and get the property which holds the array.
var dates = JSON.parse(respose_data).checkin_date
// or
var dates = JSON.parse(respose_data)['checkin_date']
If it's an object then directly access the property.
var dates = respose_data.checkin_date
// or
var dates = respose_data['checkin_date']
UPDATE : And now iterate over the array using Array#forEach or a simple for loop.
dates.forEach(function(v){
console.log(v);
})
// or
for(var i = 0;dates.length < i; i++){
console.log(dates[i]);
})
You just use method parse of JSON. After that, you receive array value for property "checkin_date". Just use it as normal array. See code below:
var json = '{"checkin_date":["2017-05-11","2017-05-18","2017-05-23","2017-05-25"]}';
var result = JSON.parse(json);
var checkin_date = result['checkin_date'];
for(var i=0; i<checkin_date.length; i++){
console.log(checkin_date[i]);
}
You can do a simple solution using arrow function:
const json = {"checkin_date":["2017-05-11","2017-05-18","2017-05-23","2017-05-25"]}
json.checkin_date.map((date) => date)
If you need it on pre-ES6 JavaScript, just do it like:
var json = {"checkin_date":["2017-05-11","2017-05-18","2017-05-23","2017-05-25"]}
json.checkin_date.map(function(date) { return date })
Both ways you will have returned all the dates from the loop.
You could:
Parse content of your request to a JavaScript object using JSON.parse().
Take property checkin_date which contains an Array with the list of dates.
Loop the Array and do whatever you need which each date.
let respose_data = '{"checkin_date":["2017-05-11","2017-05-18","2017-05-23","2017-05-25"]}';
let dates = JSON.parse(respose_data).checkin_date;
dates.forEach(date=> console.log(date))
More info on JSON.parse()
If you need to loop through each value as a date, you first need to convert the values. Take a look:
var dates = {"checkin_date":["2017-05-11","2017-05-18","2017-05-23","2017-05-25"]};
dates
.checkin_date
.map(date => new Date(date)) // here you convert the string dates to values of type Date
.forEach(date => console.log(date)) // here you loop through every Date and do whatever you want, in this case I just logged the output.

JavaScript convert string into literal comma list

Is there a way to convert "1,2" into 1,2 using native JS without some sort of wrapper?
"1,2".someMagic() \\ 1,2
Ultimately, I want to pass this as arguments to a function.
Firstly, no there is no way to convert "1,2" to literally 1,2. Because it is invalid type. 1,2 is better represented as an array
You can use .apply like below to send 1,2 as parameters (array format) to the function someMagic
someMagic.apply(context, [1,2]);
Apply would call someMagic and send 1,2 as parameters
function doSomething(param1, param2) {
return parseInt(param1)+parseInt(param2);
};
doSomething.apply(this, "1,2".split(","));
// returns 3
Perhaps this thread Converting an array to a function arguments list may be of interest to you.
Using split is the answer.
var string = "1,2";
var splitString = string.split(","); //use , as an parameter to split
http://www.w3schools.com/jsref/jsref_split.asp
Similar to user3146092's answer, this one will not rely on your function having to parseInt.
someMagic.apply(this, '1,2'.split(',').map(function(n) { return parseInt(n, 10); }));
You can create an array of numbers and pass them as your arguments, that in fact, is the best way to do it in JavaScript.
var nums = "1,2,3"
.split(",")
.map(function (num) { return parseInt(num, 10) });
Now you can pass nums as your arguments.
var str = "1,2,3,4,5,6";
var arr=[];
function process(str){
// split the string into tokens
arr = str.split(",");
// go through each array element
arr.forEach(function(val,index,ar){
// convert each element into integer
var temp = parseInt(val);
// repopulate array
arr[index] = temp;
});
}
process(str);
console.log(arr);

convert string array to integer array

I have created an array:
var endFlowArray = new Array;
for (var endIndex in flowEnd) { // <- this is just some numbers
for (var i in dateflow) { // <- same thing
var check = $.inArray(flowEnd[endIndex], dateflow[i]);
if (check >= 0) {
endFlowArray.push(i);
flowEnd[endIndex] = null;
}
}
}
How can I convert a string array of:
["286", "712", "1058"]
to integer array like:
[286, 712, 1058]
var arrayOfNumbers = arrayOfStrings.map(Number);
Strings in the console are symbolized by wrapping them in quotes. By that fact, we can assume that i is a string. Convert it to an integer and it will no longer be a string and no longer have those quotes.
endFlowArray.push(+i);
Your "numbers" in flowEnd and dateFlow are actually strings, not numbers.
To convert entire array's data type we can use map():
let numberArray = stringArray.map(Number)
try this:
let numberArray = stringArray.map(el=>parseInt(el))

Categories

Resources