Hi I have captured the data from a google spreadsheet to a new array like this
$.getJSON("https://spreadsheets.google.com/feeds/list/1IoNqeReOPKNFrYMlK2rnJVuMaLeAgnZneLbKYSQ7bs4/od6/public/values?alt=json", function(data) {
//$.getJSON("http://cors.io/spreadsheets.google.com/feeds/list/1IoNqeReOPKNFrYMlK2rnJVuMaLeAgnZneLbKYSQ7bs4/od6/public/values?alt=json", function(data) {
var len = data.feed.entry.length;
for (var i=0; i<len; i++) {
//first row "title" column
resultData[i]=new Array(9);
resultData[i][1]=data.feed.entry[i].gsx$constituency.$t;
resultData[i][2]=data.feed.entry[i].gsx$winner2010.$t;
resultData[i][3]=data.feed.entry[i].gsx$winningparty.$t;
resultData[i][4]=data.feed.entry[i].gsx$candidatename1.$t;
resultData[i][5]=data.feed.entry[i].gsx$party1.$t;
resultData[i][6]=data.feed.entry[i].gsx$candidatename2.$t;
resultData[i][7]=data.feed.entry[i].gsx$party2.$t;
resultData[i][8]=data.feed.entry[i].gsx$candidatename3.$t;
resultData[i][9]=data.feed.entry[i].gsx$party3.$t;
}
});
How can I rewrite the above as a literal array like below
var colors = [gsx$constituency, gsx$winner2010];
I am still learning to write code so will appreciate any help
I think you should update your code like below:
$.getJSON("https://spreadsheets.google.com/feeds/list/1IoNqeReOPKNFrYMlK2rnJVuMaLeAgnZneLbKYSQ7bs4/od6/public/values?alt=json", function(data) {
data.feed.entry.forEach(function(singleEntry) {
var resultData = [];
resultData.push(singleEntry);
})
});
Now you can get data like resultData[index].gsx$constituency.
Here is a way to put all values in 2-dimensional array :
var resultData = [];
$.getJSON("https://spreadsheets.google.com/feeds/list/1IoNqeReOPKNFrYMlK2rnJVuMaLeAgnZneLbKYSQ7bs4/od6/public/values?alt=json", function(data) {
var len = data.feed.entry.length, entries = data.feed.entry;
for (var i=0; i<len; i++) {
var row = [];
for (var name in entries[i]) row.push(entries[i][name].$t);
resultData.push(row);
}
console.log('result:', resultData);
});
Fiddle : http://jsfiddle.net/5zycjq7c/
$.getJSON("https://spreadsheets.google.com/feeds/list/1IoNqeReOPKNFrYMlK2rnJVuMaLeAgnZneLbKYSQ7bs4/od6/public/values?alt=json", function(data) {
var len = data.feed.entry.length;
for (var i=0; i<len; i++) {
//first row "title" column
var current = data.feed.entry[i];
resultData[i]= [current.gsx$constituency.$t, current.gsx$winner2010.$t, current.gsx$winningparty.$t, ...]; // include all here
}
});
//an ajax call to the api
jQuery(document).ready(function() {
jQuery.ajax({
url:"http://localhost:8080/activitiesWithRealData?location=%22SEA%22&startDate=%2205-14-16%22&endDate=%2205-16-16%22&theme=%22food%22",
dataType: 'JSON', type: 'GET',
success: function (data)
var viewModel;
if(data) {
viewModel = new dealsPageModel(data);
var idList = "";
for (var i = 0; i< data.packageDeal.length; i++)
{
if (i == data.packageDeal.length -1)
{ idList += data.packageDeal[i].hotelId;
}
else
{idList += data.packageDeal[i].hotelId + ',';
}
}
var searchUrl = "http://terminal2.expedia.com/x/hotels?hotelids=" + idList + "&apikey=6weV4ksGIJ5eQhd58o2XTDwVo35lZf2S";
//another call to another api to return hotel specific info
jQuery.get(searchUrl, function ( )
{
for(var i=0; i<viewModel.dealList.length; i++)
{
var hotelId = viewModel.dealList[i].hotelId;
for(var i=0; i<data.HotelInfoList.HotelInfo.length; i++)
{
var url = HotelInfoList.HotelInfo[i].ThumbnailUrl;
var name = HotelInfoList.HotelInfo[i].Name;
}
// Get the hotelid from the current deal
// Loop through the hotelinfolist.hotelInfo and find out the url for the hotel idList
//Loop through the hotelinfolist.hotelInfo and find out the name for the hotel
viewModel.dealList.push(new deal(data.packageDeal[i], url, name));
}
ko.applyBindings(viewModel);
});
}
}
})
});
You loop through data.HotelInfoList.HotelInfo but operate on HotelInfoList.HotelInfo[i].ThumbnailUrl. The data. at the beginning is missing.
Also, place data in the callback function in jQuery.get:
jQuery.get(searchUrl, function(data){
// …
your data is in data.HotelInfoList not in HotelInfoList
your loop should be like this
for(var i=0; i<data.HotelInfoList.HotelInfo.length; i++)
{
var url = data.HotelInfoList.HotelInfo[i].ThumbnailUrl;
var name = data.HotelInfoList.HotelInfo[i].Name;
}
I have tried searching but can't find anything to help, maybe my problem is too simple! Anyway, I'm running an ajax request. The data given to the request is an array. Here is my code:
var id = "1#2#3#4#5#";
var chkdId = id.slice(0, -1);
var arr = chkdId.split('#');
var checkedId = '';
var chkdLen = arr.length;
for (var i = 0; i < chkdLen; i++) {
checkedId = arr[i];
var checkedId = checkedId;
var data = {};
var year = $('#year').val();
data["year"] = year;
data['type'] = "report";
data['accidentId'] = checkedId;
console.log(data);
ajax.readData('/report/readreport', data, null,
function (result) {
console.log(result);
},
function (error) {
alert('err ' + error);
}
);
}
request array:
Object {year:"2015" type: "report", accidentId: "1"}
Object {year:"2015" type: "report", accidentId: "2"}
Object {year:"2015" type: "report", accidentId: "3"}
Object {year:"2015" type: "report", accidentId: "4"}
Object {year:"2015" type: "report", accidentId: "5"}
result:
{"data":[{"name":aaaa,"age":"15"}]}
{"data":[{"name":bbb,"age":"25"}]}
{"data":[{"name":ccc,"age":"65"}]}
{"data":[{"name":ddd,"age":"45"}]}
{"data":[{"name":eee,"age":"24"}]}
How to store the results in a single array?
Here is my Solution
var id = "1#2#3#4#5#";
var chkdId = id.slice(0, -1);
console.log(chkdId);
var arr = chkdId.split('#');
var checkedId = '';
var chkdLen = arr.length;
// here is the array
var arrayWithResults = [];
for (var i = 0; i < chkdLen; i++) {
checkedId = arr[i];
var checkedId = checkedId;
var data = {};
var year = $('#year').val();
data["year"] = year;
data['type'] = "report";
data['accidentId'] = checkedId;
console.log(data);
ajax.readData('/report/readreport', data, null,
function (result) {
console.log(result);
// here you push in the requested data
arrayWithResults.push(result);
},
function (error) {
alert('err ' + error);
}
);
}
Take the ajax out of for. This will send only One ajax request to server and minimize the load on server.
var params = [];
for (var i = 0; i < chkdLen; i++) {
checkedId = arr[i];
var data = {};
var year = $('#year').val();
data["year"] = year;
data['type'] = "report";
data['accidentId'] = checkedId;
params.push(data);
// ^^^^^^^^^^^^^^
}
ajax.readData('/report/readreport', params, null,
// ^^^^^^
function (result) {
console.log(result);
},
function (error) {
alert('err ' + error);
}
);
The result of my php is
$result = '[{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAR-14|0.59"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAR-14|0.87"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-APR-14|0.25"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-APR-14|0.67"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAY-14|0.10"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAY-14|0.03"}]';
and done json parse to it
var data = new Array();
data = JSON.parse('<?php echo $result ; ?>');
How will I get the output as
MFG_NAME[0] = ABC;
MFG_NAME[1] = XYZ;
DATE[0] = [01-MAR-14,01-APR-14,01-MAY-14];
DATE[1] = [01-MAR-14,01-APR-14,01-MAY-14];
MKT[0] = [0.59,0.25,0.10];
MKT[1] = [0.87,0.67,0.03];
Loop through data, building your arrays. First check to see if you already have a matching MFG_NAME by using indexOf(). If you have a match, use that index for the other arrays. Otherwise create new entries for each variable.
var data = [
{ MFG_NAME: "ABC", CONCATED_MKT_SHARE: "01-MAR-14|0.59" },
{ MFG_NAME: "XYZ", CONCATED_MKT_SHARE: "01-MAR-14|0.87" },
{ MFG_NAME: "ABC", CONCATED_MKT_SHARE: "01-APR-14|0.25" },
{ MFG_NAME: "XYZ", CONCATED_MKT_SHARE: "01-APR-14|0.67" },
{ MFG_NAME: "ABC", CONCATED_MKT_SHARE: "01-MAY-14|0.10" },
{ MFG_NAME: "XYZ", CONCATED_MKT_SHARE: "01-MAY-14|0.03" }
];
var MFG_NAME = [];
var DATE = [];
var MKT = [];
data.forEach(function(item) {
var parts = item.CONCATED_MKT_SHARE.split("|");
var i = MFG_NAME.indexOf(item.MFG_NAME);
if (i == -1) {
MFG_NAME.push(item.MFG_NAME);
DATE.push([parts.shift()]);
MKT.push([+parts.shift()]);
}
else {
DATE[i].push(parts.shift());
MKT[i].push(+parts.shift());
}
});
var success = MFG_NAME[0] == "ABC" &&
MFG_NAME[1] == "XYZ" &&
DATE[0].join(",") == "01-MAR-14,01-APR-14,01-MAY-14" &&
DATE[1].join(",") == "01-MAR-14,01-APR-14,01-MAY-14" &&
MKT[0].join(",") == "0.59,0.25,0.1" &&
MKT[1].join(",") == "0.87,0.67,0.03";
document.write(success);
This requires your data to be sorted by date. Your sample data is already sorted by date then name. This will still work if it's sorted by name then date, or if it's sorted by only date, not considering name at all. But, If it's not sorted by date at all, you'll need to do an extra step to sort first (which would be inefficient), or adjust the code to sort as you process the data.
$result = '[{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAR-14|0.59"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAR-14|0.87"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-APR-14|0.25"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-APR-14|0.67"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAY-14|0.10"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAY-14|0.03"}];';
var_dump(json_decode($result, true));
Maybe it's your solution?!
I guess this is what you want:
var $result = '[{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAR-14|0.59"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAR-14|0.87"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-APR-14|0.25"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-APR-14|0.67"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAY-14|0.10"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAY-14|0.03"}]';
var data = new Array();
data = JSON.parse($result);
var MFG_NAME = new Array();
var DATE = new Array();
var MKT = new Array();
var i = 0;
$.each( data, function( key, value ) {
MFG_NAME[i] = value.MFG_NAME;
var MKT_SHARE = value['CONCATED_MKT_SHARE'].split('|');
DATE[i] = MKT_SHARE[0];
MKT[i] = MKT_SHARE[1];
i++;
});
console.log(MFG_NAME[0]);
console.log(MFG_NAME[1]);
console.log(MFG_NAME);
console.log(DATE);
console.log(MKT);
Demo: http://jsfiddle.net/1n51kwze/
var MFG_NAME = [];
var DATE = [];
var MKT = [];
//For each data entry
for(i = 0; i < data.length; i++){
concatString = data[i]["CONCATED_MKT_SHARE"].split("|");
//If name not exists create date and mkt object for name instance
if(MFG_NAME.indexOf(data[i]["MFG_NAME"]) == -1){
MFG_NAME[i] = data[i]["MFG_NAME"];
DATE[i] = [];
MKT[i] = [];
DATE[i].push(concatString[0]);
MKT[i].push(concatString[1]);
}else{
//Else just add to existing
DATE[MFG_NAME.indexOf(data[i]["MFG_NAME"])].push(concatString[0]);
MKT[MFG_NAME.indexOf(data[i]["MFG_NAME"])].push(concatString[1]);
}
}
console.log(MFG_NAME[0]);
console.log(MFG_NAME[1]);
console.log(DATE[0]);
console.log(DATE[1]);
console.log(MKT[0]);
console.log(MKT[1]);
Result looks like this:
ABC
XYZ
["01-MAR-14", "01-APR-14", "01-MAY-14"]
["01-MAR-14", "01-APR-14", "01-MAY-14"]
["0.59", "0.25", "0.10"]
["0.87", "0.67", "0.03"]
Hope this helps :)
You could do that like this:
var data = [{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAR-14|0.59"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAR-14|0.87"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-APR-14|0.25"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-APR-14|0.67"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAY-14|0.10"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAY-14|0.03"}];
var MFG_NAME = [],
DATE = [],
MKT = [];
for(var i = 0; i < data.length; i++){
MFG_NAME.push(data[i].MFG_NAME);
var split = data[i].CONCATED_MKT_SHARE.split("|");
DATE.push(split[0]);
MKT.push(split[1]);
}
alert("MFG_NAME:\n" + JSON.stringify(MFG_NAME) + "\n\n" +
"DATE:\n" + JSON.stringify(DATE) + "\n\n" +
"MKT:\n" + JSON.stringify(MKT));
As you can see, this will result in 3 new arrays containing your data, separated by key.
Oh, and you don't need to declare data before adding properties to it. This'll work just fine:
var data = JSON.parse('<?php echo $result ; ?>');
I am working for some common method in javascript, for that i have to call array dynamically.
var ddlText, ddlValue, ddl, lblMesg, ddlTextCacheList_Designation, ddlValueCacheList_Designation, ddlTextCacheList_Scale, ddlValueCacheList_Scale;
function cacheDes() {
var listDes = document.getElementById("<%=List_Designation.ClientID %>");
ddlTextCacheList_Designation = new Array();
ddlValueCacheList_Designation = new Array();
for (var i = 0; i < listDes.options.length; i++) {
ddlTextCacheList_Designation[ddlTextCacheList_Designation.length] = listDes.options[i].text;
ddlValueCacheList_Designation[ddlValueCacheList_Designation.length] = listDes.options[i].value;
}
}
function cacheScale() {
var listScale = document.getElementById("<%=List_Scale.ClientID %>");
ddlTextCacheList_Scale = new Array();
ddlValueCacheList_Scale = new Array();
for (var i = 0; i < listScale.options.length; i++) {
ddlTextCacheList_Scale[ddlTextCacheList_Scale.length] = listScale.options[i].text;
ddlValueCacheList_Scale[ddlValueCacheList_Scale.length] = listScale.options[i].value;
}
}
window.onload = function () {
cacheDes();
cacheScale();
};
I want to call array ddlTextCacheList_Scale or ddlTextCacheList_Designation for same method as we know 'ddlTextCacheList_' is common only we need to put 'Scale' or 'Designation' dynamicaaly by passing parameter.
Add:
I get some errors:
I suggest you to improve your cache to store all in one object to easy access...
For example:
var CacheStorage = {};
function cache(key, list) {
CacheStorage[key] = list.map(function(option){
return {text: option.text, value: option.value};
});
}
function del(key, index) {
CacheStorage[key].splice(index, 1);
}
cache('Scale', getElementByID('...').options);
cache('Designation', getElementByID('...').options);
del('Designation', 0);