Iterate through a json encoded attay in javascript - javascript

I have an array that looks like this (using var_dump in php):
string '[{"US":"2"},{"England":"0"},{"Mexico":"0"},{"France":"0"},{"Canada":"0"},{"Spain":"0"},{"Italy":"0"},{"Australia":"0"},{"Japan":"0"},{"China":"0"},{"Korea":"0"}]'
I need to extract both columns in javascript but I obviously fail whatever I tried
This is what I tried so far:
var dbdata = <?php echo json_encode($dataset1); ?>;
for (var key in dbdata) {
for (var key2 in dbdata[key]) {
alert("Country " + key2 + " No of member is " + key);
}
}
I get the country right, but the key is the index not the column value. How should be be fixed?
Thanks

dbdata[key][key2]
Contains the number.
http://jsfiddle.net/NPTQB/
var data = [{"US":"2"},{"England":"0"},{"Mexico":"0"},{"France":"0"},{"Canada":"0"},{"Spain":"0"},{"Italy":"0"},{"Australia":"0"},{"Japan":"0"},{"China":"0"},{"Korea":"0"}];
for (var key in data) {
for (var key2 in data[key]) {
alert("Country " + key2 + " No of member is " + data[key][key2]);
}
}

Related

How to dynamically access object's property?

I have trouble accessing object' property in the example below. On the third line I'd like to have the number 42 replaced with the value of the variable devNumTemp, but so far I'm not successfull.
What is the proper way to do this? I've tried several options, but never getting any further than getting undefined.
function getTempDev(devNumTemp, devNumHum, id, description){
$.getJSON("http://someurl.com/DeviceNum=" + devNumTemp,function(result){
var array = result.Device_Num_42.states;
function objectFindByKey(array, key, value) {
for (var i = 0; i < array.length; i++) {
if (array[i][key] === value) {
$("#id").html(description + "<div class='right'>" + array[i].value + "°C" + " (" + someVariable + "%" + ")" + "<br></div>");
}
}
};
objectFindByKey(array, 'service', 'something');
});
};
You can acces to object's properties like this
var array = result["Device_Num_" + devNumTemp].states;
It's considered a good practice to test for field's existance before trying to access it:
var array = [];
if (result && result["Device_Num_" + devNumTemp]){
array = result["Device_Num_" + devNumTemp].states;
}
This way we prevent Null Pointer Exception type errors.

multi line variable in javascript

I am trying to make this javascript variable with some data from an array , but i cant figure out the right syntax to make this work..
certifications will be "Win7,Win8,PDI"
var myArray = certifications.split(",");
var data = "[{" +
for (var i in myArray)
" "id":i,"text":myArray[i]}, " +
"}]";
I'm hoping to get my data variable to look something like:
var data = "[{"id":0,"text":Win7},{"id":1,"text":Win8},{"id":2,"text":PDI}]";
Try this:
var data = JSON.stringify(certifications.split(",").map(function(value, index) {
return {
id: index,
text: value
};
}));
Maybe += is what your looking for:
var certifications = "Win7,Win8,PDI";
var myArray = certifications.split(",");
var data = "[{";
for (var i in myArray) {
data += " " +
"id" +":"+i+","+
"text" + ":"+myArray[i]+"}, ";
}
data += "}]";

How to dynamically access values in a json with jquery

Yes there are a number of threads questioning similar issues to the following, but I found very few and very little help regarding dynamic keys and pulling single values from jsons holding multiple values per key.
I have a json in which the keys are dynamic and I need to be able to call upon each separate value.
Any ideas?
json example below:
{"AppliedPrepaidBundle":{"id":["14","15","24","25","26","27","28","29","30","31"],"prepaid_bundle_id":["5","5","5","5","5","5","5","5","5","5"]},"Device":{"id":["77","77","91","91","117","117","117","117","117","124"]}}
I have played around with the following code, but currently only managed to spit out a string of values rather than individual ones:
$.each(data, function (key1, value1) {
$.each(value1, function (key, value) {
$('body').append('<li id="' + key + '">' + key1 +' ' + key +' ' + value + '</li>');
});
});
Solved with this:
json = JSON.parse(data);
for (var index in json) {
$.each(json[index], function(key,value) {
for(var i = 0; i< json[index][key].length; i++){
$('body').append('<li>' + index +' ' + key +' ' + json[index][key][i] + '</li>');
}
});
}
JSON returns an object in JavaScript. So you could do something like this:
var json = {"AppliedPrepaidBundle":{"id":["14","15","24","25","26","27","28","29","30","31"],"prepaid_bundle_id":["5","5","5","5","5","5","5","5","5","5"]},"Device":{"id":["77","77","91","91","117","117","117","117","117","124"]}};
for (var i=0; i<json.AppliedPrepaidBundle.id.length; i++) {
console.log("id"+i+": "+json.AppliedPrepaidBundle.id[i]);
}
This prints out all the values of the ID object: 14, 15, 24, 25, etc
Use JSON.parse to create an object. (See How to parse JSON in JavaScript). Then loop through the properties with for (x in yourObject) { ... }.
var jsonObject = JSON.parse('your JSON-String');
for (property in jsonObject) {
// do something with jsonObject[property]
console.log(property + ' ' + jsonObject[property]);
}
you can work with the javascript basic functionality:
http://jsfiddle.net/taUng/
var data = {"AppliedPrepaidBundle":{"id":["14","15","24","25","26","27","28","29","30","31"],"prepaid_bundle_id":["5","5","5","5","5","5","5","5","5","5"]},"Device":{"id":["77","77","91","91","117","117","117","117","117","124"]}};
for (var dataIndex in data) {
console.log(dataIndex, data[dataIndex]);
var subData = data[dataIndex];
for (var subDataIndex in subData) {
console.log(subDataIndex, subData[subDataIndex]);
}
}
And so on...
When your a fit in javascript you can also work with Recursion to don't repeat yourself. (http://en.wikipedia.org/wiki/Dont_repeat_yourself)
From this example you can access all elements
var json = {"AppliedPrepaidBundle":{"id":["14","15","24","25","26","27","28","29","30","31"],"prepaid_bundle_id":["5","5","5","5","5","5","5","5","5","5"]},"Device":{"id":["77","77","91","91","117","117","117","117","117","124"]}};
for (var i=0; i<json.AppliedPrepaidBundle.id.length; i++) {
$('body').append("<li>AppliedPrepaidBundle id"+i+": "+json.AppliedPrepaidBundle.id[i]+'</li>');
}
for (var i=0; i<json.AppliedPrepaidBundle.prepaid_bundle_id.length; i++) {
$('body').append("<li>PrepaidBundleid"+i+":"+json.AppliedPrepaidBundle.prepaid_bundle_id[i]+'</li>');
}
for (var i=0; i<json.Device.id.length; i++) {
$('body').append("<li>Device id"+i+": "+json.Device.id[i]+'</li>');
}
Here is the fiddle

Problem looping through nested JavaScript objects and arrays

i need display the child value, but it display [object, object] like that so
Here my code:
var jsonObj = {"department":{
"Title1":[
{"child1":"Green",
"child2":"Yellow"
},
{"child3":"Black",
"child4":"White"
}
],
"Title2":[
{"child5":"Violet",
"child6":"purple"
},
{"child7":"Pink",
"child8":"Orange"
}
]
}
}
$(document).ready(function() {
var treeList = "";
treeList = "<ul id=\"createTree\">";
for(var key in jsonObj){
for(var subKey in jsonObj[key]){
alert(subKey);
//for(i=0; i<jsonObj[key].length;i++ ) {
treeList += ("<li>" + subKey + "<ul><li>"+jsonObj[key][subKey]+"</li></ul></li>");
//var b = $(c).text();
alert(treeList);
}
}
treeList += "</ul>";
$('#tree').append(treeList);
});
As Quentin said you need to keep drilling down, first into the array then into the objects contained within the array. The code below should access all the variables held in the JSON, you might have to restructure the HTML it outputs to get it looking as you want -
$(document).ready(function() {
var treeList = "";
treeList = "<ul id=\"createTree\">";
for(var key in jsonObj){
for(var subKey in jsonObj[key]){
alert(subKey);
for(i=0; i<jsonObj[key][subKey].length;i++ ) {
for(var arrayKey in jsonObj[key][subKey][i]){
treeList += ("<li>" + subKey + " - " + arrayKey + " - "+jsonObj[key][subKey][i][arrayKey]+"</li></ul></li>");
}
//var b = $(c).text();
alert(treeList);
}
}
}
treeList += "</ul>";
$('#tree').append(treeList);
});
The first jsonObj[key][subKey] will be jsonObj.department.Title1. This is an array.
When you stringify an array, it will, by default, produce the generic "This is an object" text.
If you want to display the data in it, you will have to keep going down to get at the strings.

JSON, Javascript & Dynamically Created & Populated Tables

I've got the following JSON structure that defines a table and it's data.
var arrTable =
[{"table": "tblConfig",
"def":
[{"column": "Property", "type": "TEXT NOT NULL"},
{"column": "Value", "type": "TEXT NOT NULL"}],
"data":
[{"Property": "VersionNumber", "Value": "1.0"},
{"Property": "ReleaseDate", "Value": "2010-01-01"}]
}]
The code describes a table named "tblConfig" with two columns, "Property" and "Value" both are type "TEXT NOT NULL". The table has two rows of data.
Property_______Value_____
VersionNumber 1.0
ReleaseDate 2010-01-01
Below is my Javascript code to create and populate the table. It builds the create table SQL great but I'm having trouble with the populate function.
dbController.updateDatabase = function () {
this.db.transaction(function (transaction) {
//load data.json
var dbDefs = dbController.jsonObject(url + "data.json")
//parse array "table"
eval(dbDefs);
for (var i in arrTables) {
createTable(arrTables[i].table, arrTables[i].def, arrTables[i].data);
}
//create table
function createTable(table, arrDef, arrData) {
var arrColumns = [];
var strSQL = "CREATE TABLE " + table + " (";
for (var j in arrDef) {
arrColumns.push(arrDef[j].column);
strSQL += arrDef[j].column + " " + arrDef[j].type + ", ";
}
strSQL = strSQL.substring(0, strSQL.lastIndexOf(",")) + ")";
transaction.executeSql(strSQL, [],
function () {
console.log(table + " created.");
populateTable(table, arrData);
return;
},
dbController.errorHandler
);
}
//populate table
function populateTable(table, arrData) {
...
}
});
};
I want to be able to get the column names ("Property" & "Value") out of the "data" object and use them in the insert SQL string. I thought something like this would work.
//populate table
function populateTable(table, arrColumns, arrData) {
var strVal;
var arrVal;
for (var k in arrData) {
strVal = "?,";
arrVal.push(arrData[k]. ~~ KEY VALUE NAME ~~ )
}
var strSQL = "INSERT INTO " + table + " (" + strCol + ") ";
strSQL += "VALUES (" + strVal.lastIndexOf(",") + ");";
transaction.executeSql(strSQL, arrVal, null, dbController.errorHandler);
console.log(" " + table + " populated.");
}
The bugger is the bolded statement. I've tried using .hasOwnProperty() on arrData but that only returns 0 and 1, not the words "Property" and "Value". I don't want to use the "arrData[k].Property" notation because there are many more tables in the schema and I don't want to write create and insert statements for each table.
Any help is greatly appreciated.
Thanks to everyone for their help and head-scratching due to my late-night post. My intention with this function was to have a JSON object that defined multiple tables and held the table's data. Since none of the tables have the same number of columns or column names I had to devise a way of getting the data out of "data" without using the object.member syntax. I had forgotten about the object["member"] syntax.
Here's the solution.
dbController.updateDatabase = function (a) {
this.db.transaction(function (transaction) {
//load data.json
var dbDefs = dbController.jsonObject(dbController.dbFolder + "data.json")
//parse array "table"
eval(dbDefs);
for(var i in arrTables) {
createTable(arrTables[i].table, arrTables[i].def, arrTables[i].data);
}
//create table
function createTable(table, arrDef, arrData){
var arrColumns = [];
var strSQL = "Create Table " + table + " (";
for(var j in arrDef) {
arrColumns.push(arrDef[j].column);
strSQL += arrDef[j].column + " " + arrDef[j].type + ", ";
}
strSQL = strSQL.substring(0, strSQL.lastIndexOf(",")) + ")";
transaction.executeSql(strSQL, [],
function() {
console.log(table + " created.");
populateTable(table, arrColumns, arrData);
return;
},
dbController.errorHandler
);
}
//populate table
function populateTable(table, arrColumns, arrData) {
for (var k in arrData) {
var arrVal = [];
var strVal = "";
for (var l = 0; l < arrColumns.length; l++) {
strVal += "?,";
arrVal.push(arrData[k][arrColumns[l]])
}
var strSQL = "Insert Into "+table+" (" + arrColumns.toString()+") ";
strSQL += "Values ("+strVal.substring(0, strVal.lastIndexOf(","))+");";
transaction.executeSql(strSQL, arrVal, null, dbController.errorHandler);
}
console.log(" " + table + " populated.");
}
});
};
I'm making some assumptions here, but try changing:
for (var k in arrData) {
strVal = "?,";
arrVal.push(arrData[k]. ~~ KEY VALUE NAME ~~ )
}
var strSQL = "INSERT INTO " + table + " (" + strCol + ") ";
strSQL += "VALUES (" + strVal.lastIndexOf(",") + ");";
to:
for (var i =0; i < arrColumns.length; ++i) strVal += ',?';
for (var k in arrData)
{
arrVal[k] = [];
for (var i in arrColumns)
arrVal[k].push (arrData[k][arrColumns[i]]);
}
var strSQL = "INSERT INTO " + table + " (" + strCol + ") ";
strSQL += "VALUES (" + strVal.substr(1) + ");";
If I'm correct in thinking that transaction.executeSql(strSQL, arrVal, null, dbController.errorHandler); accepts multiple records, then this should work fine. Otherwise, call
transaction.executeSql(strSQL, arrVal[0], null, dbController.errorHandler);
instead
Don't you just want to look at the first row of your 'data' element and enumerate through those keys (assuming all the rows are the same)?
for (var k in arrData[0]) {...
In Javascript, and time you have an object with members that you can access via obj.member, you can also access it as obj["member"]. Objects in JavaScript are essentially just hash tables with the ability to call methods on them (which are also just entries in the hash table), and a prototype based inheritance system.
Anyhow, that means that you can use for ... in to iterate over the properties in that hash table, and pull out the keys.
So, if I understand what you're trying to do correctly, you could just do something like this (note that the structure of this loop is somewhat different than the one in your question, as you're going to need one INSERT statement for each row to insert, while your loop had the construction of the INSERT statement outside of the loop over the data rows):
function populateTable(table, data) {
for (var k in data) {
var queryArgs = [];
var argArray = [];
var columns = [];
for (var col in data[k]) {
queryArgs.push('?');
columns.push(col);
argArray.push(data[k][col]);
}
var SQL = "INSERT INTO " + table + " (" + columns + ") VALUES " +
"(" + queryArgs + ");";
alert(SQL + " [" + argArray + "]")
}
}

Categories

Resources