Looping through dynamic JSON data using javascript - javascript

I am trying to display JSON data but the key value is dynamic it varies from one POST request to another my data hierarchy is as shown in diagram:
This is the part of the code I am running,Can anyone suggest me how to display JSON data where key showed in redbox gonna change for every POST request
$.ajax({
type: "POST",
url: "/",
dataType:'json',
data : { 'perfid': valueOne, 'hostname': $("#host").val(), 'iteration': valueThree},
success: function(data) {
$('#img1').hide();
var k = data[$("#host").val()].iscsi_lif.result.sectoutput.sect.length;
for(var i = 0; i < k; i++) {
var obj = k[i];
console.log(obj);
var iscsi = parseInt(data[$("#host").val()].iscsi_lif.result.sectoutput.sect.obj.avg_latency);
console.log(iscsi);
}
While running above snippet I am getting following error message :
data[$(....).val(...)].iscsi_lif.result.sectoutput.sect is undefined

You can use a "for in" loop to iterate over the keys of an object without having to specify the key names.
for( var key in myObject){
myValue = myObject[key];
// key will be your dynamically created keyname
}
So your code could be similar to the following:
...
success: function(data) {
$('#img1').hide();
var obj = data[$("#host").val()].iscsi_lif.result.sectoutput.sect;
for(var key in obj) {
if(obj.hasOwnProperty(key)){
var iscsi = parseInt(obj[key].avg_latency);
console.log(iscsi);
}
}
}

Solution Suggestion:
for (var key in object) {
if (object.hasOwnProperty(key)) {
var element = object[key];
}
}
Yet, in your situation, maybe you'll have to do this multiple times, so I would try to extract a generic function to do this and "normalize" the processing result to an expected format that wouldn't change.
The function will only run when the expected keys exist and since the forin loop uses the object keys, every object is processed dynamically.

This should work:
var k = data[$("#host").val()].iscsi_lif.result.sectoutput.sect;
for (var i = 0; i < k.length; i++) {
var obj = k[i];
console.log(obj);
var iscsi = parseInt(data[$("#host").val()].iscsi_lif.result.sectoutput.sect[obj].avg_latency);
console.log(iscsi);
}
The variable should be put inside brackets.
Also, it seemed to me that k was simply defined as length of an array, I removed that and put it to the for loop.

Since you have obj defined as varible you should use [], so it will be [obj], e.g :
var iscsi = parseInt(data[$("#host").val()].iscsi_lif.result.sectoutput.sect[obj].avg_latency);
Hope this helps.

Related

Get JSON stringify value

I have JSON stringify data like this :
[{"availability_id":"109465","date":"2017-02-21","price":"430000"},{"availability_id":"109466","date":"2017-02-22","price":"430000"},{"availability_id":"109467","date":"2017-02-23","price":"430000"}]
I want to get only price value of that data. I have tried this way but it doesn't work.
var stringify = JSON.stringify(values);
for(var i = 0; i < stringify.length; i++)
{
alert(stringify[i]['price']);
}
How could I to do that ?
This code will only fetch the price details.
var obj = '[{"availability_id":"109465","date":"2017-02-21","price":"430000"},{"availability_id":"109466","date":"2017-02-22","price":"430000"},{"availability_id":"109467","date":"2017-02-23","price":"430000"}]';
var stringify = JSON.parse(obj);
for (var i = 0; i < stringify.length; i++) {
console.log(stringify[i]['price']);
}
Observation :
If you want to parse the array of objects to get the property value you have to convert in into JSON object first.
DEMO
var jsonStringify = '[{"availability_id":"109465","date":"2017-02-21","price":"430000"},{"availability_id":"109466","date":"2017-02-22","price":"430000"},{"availability_id":"109467","date":"2017-02-23","price":"430000"}]';
var jsonObj = JSON.parse(jsonStringify);
for(var i = 0; i < jsonObj.length; i++)
{
alert(jsonObj[i]['price']);
}
you will geting a stringified object like this
var obj='[{"availability_id":"109465","date":"2017-02-21","price":"430000"},
{"availability_id":"109466","date":"2017-02-22","price":"430000"},
{"availability_id":"109467","date":"2017-02-23","price":"430000"}]';
parse your obj using JSON.parse(object)
then apply this loop ad let me know it get any error
lie this
var parseObject = JSON.parse(object);
instead of using stringify before selecting the data you should use your loop directly on the values array.
For example :
var priceArray = array();
values.forEach (data) {
alert(data['price'];
priceArray.push(data['price']);
}
stringify = JSON.stringify(values);
stringifiedPriceArray = JsON.stringify(priceArray);
Once stringified, you can't reach the data in your array

Javascript Getting value from exact field from associative array

I have an associative array - indexed by dates. Every element holds another array.
[03/16/2015: Array[3], 03/17/2015: Array[3], 03/18/2015: Array[3], 03/19/2015: Array[3]]
I created it with this code:
array[cellDate][i]=cellText;
How can I get the value for example from cell 03/16/2015 array[2] ??
var text=array['03/16/2015'][2];
With this line of code I got an error.
EDIT:
http://www.traineffective.com/schedule/
I store in that array title of blocks dropped in the schedule (title of block of 'empty' value if cell is empty)
What I want to achive is remeber the order of the blocks for particular weeks , and when user changes week with arrows it loads block based on date withdrowed from array.
Code where I create array :
function saveWeekToArray(array){
var cellDate;
var cellText;
var tmpText;
var i;
workoutsTD.each(function(){
cellDate=$(this).attr("data-day");
array[cellDate]=['','',''];
i=0;
$(this).children('.workout-cell').each(function(){
if (!$(this).hasClass('workout-cell-empty')){
cellText=$(this).find('span').text();
array[cellDate][i]=cellText;
} else {
array[cellDate][i]='empty';
}
i++
});
});
}
Code where I load data from array (One with the error )
function loadBlocksFromArray(array){
var cellDate;
var cellText;
var tmpText;
var i;
workoutsTD.each(function(){
cellDate=$(this).attr("data-day");
i=0;
$(this).children('.workout-cell').each(function(){
if ((array[cellDate][i])!='empty'){
cellText=array[cellDate][i];
$(this).append(createBlock(cellText));
$(this).removeClass('workout-cell-empty');
}
i++;
});
});
}
When you will click sumbit button in console log you will see the structure of array.
I got error while changing the week its :
enter code hereUncaught TypeError: Cannot read property '0' of undefined
In Javascript, there is no concept of an associative array. You either have arrays (which are indexed by numbers) or you have Objects (whose elements are indexed by strings).
What you instead want is an object containing all of your arrays. For example:
var data = {
'3/4/2015' : ['val1', 'val2', 'val3'],
'3/8/2015' : ['val1', 'val2', 'val3']
};
Then you can access your elements in the way that you want:
var ele = data['3/4/2015'][1];
https://jsfiddle.net/x9dnwgwc/
That is the effect what I wanted achive. Thanks for hint Harvtronix!
var jsonObj = { workout : {} }
var i;
var k;
var workoutArray = [];
for(i=1; i<=7; i++){
var newWorkout = i+ "/12/2015";
for (k=0; k<=2; k++){
var newValue = "workoutTitle" + k;
workoutArray[k]=newValue;
}
jsonObj.workout[newWorkout]=workoutArray;
}
console.log(jsonObj);
for(i=1; i<=7; i++){
var newWorkout = i+ "/12/2015";
var tmpArray= jsonObj.workout[newWorkout];
console.log(tmpArray);
}

Merging JSON data from multiple URL's and sorting them based on a key

I need some help with Javascript. I have some data that I received from youtube APIs. The data is retrieved from the below URL's (I only showed 2 but I get from multiple other channels too)
https://www.googleapis.com/youtube/v3/search?key=AIzaSyDuS9LWv86VFCFr4ZD_Kwp5--Zi6YKo_rM&part=snippet,id&order=date&maxResults=50&channelId=UCpVm7bg6pXKo1Pr6k5kxG9A
https://www.googleapis.com/youtube/v3/search?key=AIzaSyDuS9LWv86VFCFr4ZD_Kwp5--Zi6YKo_rM&part=snippet,id&order=date&maxResults=50&channelId=UCLQZTXj_AnL7fDC8sLrTGMw
Every item in these json files has "publishedAt" value. Now I want to merge the data from both the JSON files and sort the list based on the "publishedAt" key i.e., the latest uploaded videos shown first.
Here is what I have currently which works perfectly for one file (I didn't do any magic, the URL itself sorts the items based on date)
$.getJSON(sourceUrl, function (data) {
//console.log(data);
//var you_data = JSON.stringify(data);
var videosCount = data.items.length;
console.log("The number of videos is: " + videosCount);
for ( i = 0 ; i < videosCount; i++) {
var title = data.items[i].snippet.title;
var url = "https://www.youtube.com/watch?v=" + data.items[0].id.videoId;
$("#reply").append(" " + title + "<br><br><br>");
//console.log(title);
//console.log(url);
};
});
How do I get this done?
EDITED (my thoughts):
Something that I can think of is using nested objects. I can create a new object that two looks something like:
grand_parent_object = { {'publishedAt':xxxxxxxx, 'wholeItem':{the whole item as shown in the JSON file}}, {'publishedAt':xxxxxxxx, 'wholeItem':{the whole item2 as shown in the JSON file}}, etc}
here the parent_object is {'publishedAt':xxxxxxxx, 'wholeItem':{the whole item as shown in the JSON file}}
Maybe I should sort the parent_objects based on their 'publishedAt' values first and then that should do the job???? PS: 'publishedAt' in parent_object is the same as 'publishedAt' in the 'wholeItem' value.
Solution:
I used Ross's logic and it worked. I had issues with .getJson since it wouldn't update the global variable, wholearray. So I used .ajax and it worked. Here is my working code:
function getAjaxData(sourceUrl) {
$.ajax({
async:false,
url:sourceUrl,
success: function(data) {
var videosCount = data.items.length;
for ( var i = 0 ; i < videosCount; i++) {
var tempobject = {};
tempobject.published = data.items[i].snippet.publishedAt;
tempobject.wholeItem = data.items[i];
wholearray.push(tempobject);
}
}
});
}
One solution is to create a new array of object literals, then sort the array based on the key:
var array = [];
$.getJSON(url, function(data){
for (var i=0; i<data.length; i++){
var object = {}
object.published = data.items[i].snippet.publishedAt
object.wholeItem = data.items[i]
array.push(object);
}
})
$.getJSON(otherUrl, function(data){
for (var i=0; i<data.length; i++){
var object = {}
object.published = data.items[i].snippet.publishedAt
object.wholeItem = data.items[i]
array.push(object);
}
})
Have a listener that waits for both AJAX calls to finish, then you can sort:
array.sort(function(a,b) { return a.published - b.published; });
This question gives more info on sorting
This may not be the most efficient way, but it's the first that comes to mind and will work swell!

jQuery serialize and validate data

I have the following line returned from serializing data
rl=250&first_name=&surname=&email=&phone=&country_id=1&agency_name=&sitename=
I want to loop through these and check if there is an empty field and if there is then I can throw an error.
I can get the index and element but the element is rl=250 or first_name=
How can I check if the element is set or not. I have also tried using serializeArray() but it returns me [Object, Object, Object, Object, Object, Object, Object, Object] which should have the name and value but I do not know how to access these
You need to split this using '&'. Then you should apply for loop and in that loop you again need to split that string with '=' sign. Then if you get second element of loop as blank, you can throw error
serializeArray is a good way.
https://api.jquery.com/serializeArray/
As you can see, it returns arrays of objects so in your case it is something like tihs:
[
{
rl: 250
},
{
first_name: undefined
}
]
After this you can iterate on the array of the objects with for loop on the values.
I found this function by Jack alan
https://stackoverflow.com/a/16215183/1430587
function deparam(query) {
var pairs, i, keyValuePair, key, value, map = {};
// remove leading question mark if its there
if (query.slice(0, 1) === '?') {
query = query.slice(1);
}
if (query !== '') {
pairs = query.split('&');
for (i = 0; i < pairs.length; i += 1) {
keyValuePair = pairs[i].split('=');
key = decodeURIComponent(keyValuePair[0]);
value = (keyValuePair.length > 1) ? decodeURIComponent(keyValuePair[1]) : undefined;
map[key] = value;
}
}
return map;
}
You could do something like this:
$(document).ready( function(e) {
$("#frm-login").submit(function() {
var DATA = $(this).serializeArray();
len = DATA.length,
dataObj = {};
for (i=0; i<len; i++) { // acceesing data array
dataObj[DATA[i].name] = DATA[i].value;
}
if ( !dataObj['user-id'].trim() || !dataObj['user-pass'].trim() ) { //cheking if empty field
alert('empty');
}else{
alert('full');
}
//console.log(DATA);
$.ajax({
type: "POST",
url: 'user-login-process.php',
data: DATA,
success: function(response){
//alert(response); // show response from the php script.
}
});
return false; // avoid to run the actual submit of the form.
});
}); //document

Jquery post a Array

I am having a Array which is generated by my Javascript in run time.
once that array is full with all the values I want to send it using POST to the server.
How can I do that ...
Pseudo code:
for(i=0;i<result.data.length;i++)
{
result.data[i].id
}
$.post("receiver.php", { xxxxx }, function(data){ console.log(data);});
How can I get that xxxx updated in the post
I checked the documentation in jquery but they are expecting to give all the values in POST.I do not want to do that.
Also, I want to send post only once so that traffic will be less.
EDIT
You can use join() to get all your array values converted to a string, using some char to separate it.
EDIT 2: As Kumar said he was using 2 arrays
var idsArray;
var namesArray;
for(i=0;i<result.data.length;i++)
{
idsArray[] = result.data[i].id;
namesArray[] = result.data[i].name;
}
var ids = idsArray.join(",");
var names = namesArray.join(",");
$.post("receiver.php", { ids:ids, names:names }, function(data){ console.log(data);});
similar to iBlue's comment, You can just send an object with post; you don't have to define the object in the post function, { } are simply the delimiters to define objects, which are similar to PHP associative arrays:
$.post('reciever.php', myData, function(data){ /*callback*/ });
The only thing is that you setup myData as an object like follows:
myData = {
0: 'info',
1: 'info'
}
//or even something like this
myData = {
someProp: 'info',
someProp2: {
anotherProp: 'moreInfo'
}
}
you can also use non-numerical indexes with objects, and easily add properties:
myData[2] = 'info';
or you can loop through it, just in a slightly different way:
for(i in myData){
myData[i]; //Do something with myArr[i]
}
the for in loop will also loop through non-numerical properties. And you can still get the length of myData by
myData.length;
EDIT:
Instead of sending a string:
IDs = {}
Names = {}
for(var i = 0; i < result.data.length; i++){
IDs[i] = result.data[i].id;
Names[i] = result.data[i].name;
}
$.post('reciever.php', {IDs: IDs, Names: Names}, function(data){});
In the PHP file you would access them like so
$_POST['IDs'][0] = "some id";
$_POST['Names'][0] = "some name";
EDIT:
Actaully I think the indexes are sent as strings, so might have to do
$_POST['IDs']['0']
Not sure, but it seems like you want to do this:
var sendObj = {};
for (var i=0; i<result.data.length; i++) {
var id = result.data[i].id,
name = result.data[i].name; // or some similiar computation
sendObj[name] = id;
}
$.post("receiver.php", sendObj, function(data){ console.log(data);});
This will send the result.data as name=id-value-pairs.

Categories

Resources