splitting json array in javascript not working - javascript

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.

Related

convert json values in comma separated string using javascript

I am calling a third party web api, which returns data like this:
{"name":"Marine Lines","name":"jerry"}
I would like to convert this to a Json array, I could do a split by comma first and then by ":". but wondering if there are some better ways?
If the Web API return an object, then you can directly use dot-notation to access the value.
var x = {"name":"Marine Lines","name":"jerry"};
var name = x.name;
console.log(name);
Else if it is a string then you can parse it first using JSON.parse() and then do the same thing.
var x = '{"name":"Marine Lines","name":"jerry"}';
x = JSON.parse(x);
var name = x.name;
console.log(name);
First of all, your object has the name key twice, which means only the latter will be saved. As regards saving your object's values in an array, the following will do:
var
object = {"a": "Marine Lines", "b": "jerry"},
array = [];
/* Iterate over every enumerable property of the object. */
for (var key in object) {
/* Insert the value in the array. */
array[array.length] = object[key];
}
/* Log the created array. */
console.log(array);

Fetch localstorage value in array

I am saving value in localstorage as shown below
key = profskill , value = "a,b,c"
In my test.ts file, I have declared array but I am unable to fetch the result in it. Code shown below:
getskills: Array<string> = [];
this.getskills = localStorage.getItem("profskill");
but this is giving error:
Type 'string' is not assignable to type 'string[]'
I want to fetch value like this:
console.log(this.getskills[0]);
The LocalStorage can only store strings, not objects or arrays. If you try to store an array, it will automatically be converted to a string. You need to parse it back to an array :
JSON.parse( localStorage.getItem("profskill") )
Since, you want the comma separated value to be represented as a array of strings for this.getskills use split on the value of the localStorage
Here is a sample example
//say we get the value 'a,b,c' from localStorage into the temp variable
//var temp = localStorage.getItem(profskill);
var temp= 'a,b,c';
this.getskills = temp.split(',');
console.log(this.getskills[0]);
localStorage only supports strings. Use JSON.stringify() to set the data in storage and JSON.parse() to get the data from storage and then use split(",") to split the comma separated data.
var obj = "a,b,c";
localStorage.setItem("profskill", JSON.stringify(obj));
var getskills = [];
getskills = JSON.parse(localStorage.getItem("profskill")).split(",");
console.log(getskills[0]);
First get the data from the LocalStorage:
var DataTableValue = JSON.parse(localStorage.getItem('dataTableValue'));
Then, store in an Array:
var tempArray = new Array();
for (var i = 0; i < DTarray.length; i++) {
tempArray.push(DTarray[i]);
}
All data will be stored in the variable tempArray.

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)

javascript convert string to data

I have JavaScript code below.
var data = "[{"PR_ID":23096,"P_ID":23014},{"PR_ID":33232,"P_ID":23014},{"PR_ID":33308,"P_ID":23014},{"PR_ID":33309,"P_ID":23014}]";
I need convert the string to an data by delete the "" surrounding the array stored as "data" in JavaScript so after convert it suppose like below:
var data = [{"PR_ID":23096,"P_ID":23014},{"PR_ID":33232,"P_ID":23014},{"PR_ID":33308,"P_ID":23014},{"PR_ID":33309,"P_ID":23014}];
How to make the convert?
To convert a JSON object to Javascript object use:
var data = '[{"PR_ID":23096,"P_ID":23014},{"PR_ID":33232,"P_ID":23014},{"PR_ID":33308,"P_ID":23014},{"PR_ID":33309,"P_ID":23014}]';
JSON.parse(data);
But first change the double quote to single quote, otherwise the JSON object wont be a valid JSON.
After this you can walk the array in the following way:
var jsonParsed = JSON.parse(data);
for(var val in jsonParsed) {
if(jsonParsed.hasOwnProperty(val)) {
// do something with the values
}
}

Filling multidimensionnal array in JavaScript

I've a little problem in JavaScript.
I need to get an array width date as keys and events as values.
In PHP I would do something like this :
$var = new array();
Loop
$var[$date][] = $event;
End loop
Do you know what I mean ?
Thanks,
Regards
In javascript, you can create a data structure like that this way:
var events = {
'2009-09-09': [],
'2010-10-10': [],
'2011-11-11': []
};
The events = { ... } is an object literal in javascript. Objects in javscript act very much like hashes with properties as keys, so this is essentially going to act as a hash keyed on dates. Each date is initialized with an empty array.
And you can fill it up with events like this
events[date].push(event);
If you don't know the dates ahead of time, you can dynamically fill the hash. So, you'd start with just an empty hash:
var events = {};
Then you'd check for the date key every time you go to add an event, like this:
if (!(date in events)) events[date] = [];
events[date].push(event);
The date in events checks to see if the key exists, and the ! negates it. So if the date key does not exist, it initializes the date key with an empty array. Then it pushes the event for that date as normal.
In Javascript key-value mappings are handled by Objects. An empty object is just {}. You can do this sort of thing like (note that var is a reserved word in Javascript so I can't copy your example exactly):
var variable = {};
var date_list = [1,2,3];
var event_list = [4,5,6];
for (i in date_list){
var key = date_list[i];
var value = event_list[i];
variable[key] = value;
}
// variable now contains: {1:4, 2:5, 3:6}
console.log(variable[1]);
// prints 4
EDIT: That's the basic syntax. If you want to have an array for each key, just do something like that but with arrays instead of numbers in event_list. For example:
my_dates = {'2011': [1,2,3], '2010': [6,7,8]}
To add an element to a list you can use the push javascript method of array objects...
events_by_date = {};
...
for (var i=0; i<events.length; i++) {
if (!events_by_date[events[i].date]) {
// This is the first event on this date
// so create the list
events_by_date[events[i].date] = [];
}
// Add the event to the list of events in that date
events_by_date[events[i].date].push(events[i]);
}

Categories

Resources