How to dynamically access values in a json with jquery - javascript

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

Related

I am trying to fetch objects from a main object

I am trying to fetch objects from a main object. An array in the main object holds
these other objects, I can access the first element by calling 'oData.events.event[0]' but I would like to loop through to get [1], [2], [3] and so on.
//this works
var collection = oData.events.event[0];
$("<li>description: " + collection.description + "</li>").appendTo("#shower");
//this does not work :(
var collection = oData.events.event[0];
var output = "<ul>";
for (var i = 0; i < collection.length; i++)
{
output += "<li>" + collection.description + "</li>";
$(output).appendTo("#shower");
collection = collection + 1 //shift to next array
}
output += "</ul>";
Maybe use a foreach loop
oData.events.event.forEach(function(result) {
console.log(result);
});
Alternatively, try jQuery's .each() function:
$.each(oData.events.event, function(index, value) {
console.log( index + ": " + value );
});
EDIT: It's worth noting that the output of these calls will be an object - you still have to access the data beneath the objects you've looped to!
Fiddle here - however, you can do something like this...
var oData = {
events: {
event: [{ description: '1' },
{ description: '2' },
{ description: '3' }]
}
}
var collection = oData.events.event;
var output = "<ul>";
collection.forEach(function(item, i, arr) {
output += "<li>" + item.description + "</li>";
if (i === arr.length-1) {
output += "</ul>";
$("#shower").append(output);
}
});

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.

Append JavaScript array data into div

I have the following JavaScript array data:
[{'id:1'},{"info":"Name"}"]
[{'id:2'},{"info":"LastName"}"]
How do I loop through this and insert the data into a div? I tried something like this,but no success:
for(var i=0; msg.length<i; i++){
$('#results_box').append(msg[i].id);
$('#results_box').append(msg[i].info);
}
Correct your JSON to proper format:
var array = [{id:1,info:"Name"},{id:'2',info:"LastName"}]
then:
for(var i=0; i<array.length; i++)
{
$('#results_box').append('<p>' + array[i].id + '=' + array[i].info + '</p>');
}
html
<div id="results_box"></div>
Fiddler

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.

post data from table row like json format

this is related to my last question(
NOTE: I already got some good answers there). I'm doing a program that will filter. I didn't include this question because i thought that it is easier for me to add text as long as i know how to get the data from the row. But to my dismay, I wasn't able to code a good program til now.
Im currently using this javascript code (thanks to Awea):
$('#out').click(function(){
$('table tr').each(function(){
var td = '';
$(this).find('option:selected').each(function(){
td = td + ' ' + $(this).text();
});
td = td + ' ' + $(this).find('input').val();
alert(td);
});
})
my question is: How to add text before the data from the row? like for example, this code alert
the first row like data1.1 data1.2 data1.3,
then the second row like data2.1 data2.2 data2.3,
I want my output to be displayed like this
[
{"name":"data1.1","comparison":"data1.2", "value":"data1.3"},
{"name":"data2.1","comparison":"data2.2", "value":"data2.3"},
{"name":"data3.1","comparison":"data3.2", "value":"data3.3"}
{.....and so on......}]
but before that happen, i want to check if all the FIRST cell in a row is not empty. if its empty, skip that row then proceed to next row.
is there somebody can help me, please...
Building on my answer to your previous question, see http://jsfiddle.net/evbUa/1/
Once you have your data in a javascript object (dataArray in my example), you can write the JSON yourself, per my example, but you will find it much easier to use a library such as JSON-js (see this also).
// object to hold your data
function dataRow(value1,value2,value3) {
this.name = value1;
this.comparison = value2;
this.value = value3;
}
$('#out').click(function(){
// create array to hold your data
var dataArray = new Array();
// iterate through rows of table
for(var i = 1; i <= $("table tr").length; i++){
// check if first field is used
if($("table tr:nth-child(" + i + ") select[class='field']").val().length > 0) {
// create object and push to array
dataArray.push(
new dataRow(
$("table tr:nth-child(" + i + ") select[class='field']").val(),
$("table tr:nth-child(" + i + ") select[class='comp']").val(),
$("table tr:nth-child(" + i + ") input").val())
);
}
}
// consider using a JSON library to do this for you
for(var i = 0; i < dataArray.length; i++){
var output = "";
output = output + '{"name":"data' + (i + 1) + '.' + dataArray[i].name + '",';
output = output + '"comparison":"data' + (i + 1) + '.' + dataArray[i].comparison + '",';
output = output + '"value":"data' + (i + 1) + '.' + dataArray[i].value + '"}';
alert(output);
}
})
There are two things you need to do here. First get the data into an array of objects, and secondly get the string representation.
I have not tested this, but it should give you a basic idea of what to do.
Edit Please take a look at this JS-Fiddle example I've made. http://jsfiddle.net/4Nr9m/52/
$(document).ready(function() {
var objects = new Array();
$('table tr').each(function(key, value) {
if($(this).find('td:first').not(':empty')) {
//loop over the cells
obj = {};
$(this).find('td').each(function(key, value) {
var label = $(this).parents('table').find('th')[key].innerHTML;
obj[label] = value.innerHTML;
});
objects.push(obj);
}
});
//get JSON.
var json = objects.toSource();
$('#result').append(json);
});
var a = [];
a[0] = "data1.1 data1.2 data1.3"
a[1] = "data1.6 data1.2 data1.3"
var jsonobj = {};
var c = []
for (var i = 0;i
alert(c); //it will give ["{"name":"data1.1","comp...1.2","value":"data1.3"}", "{"name":"data1.6","comp...1.2","value":"data1.3"}"]
u have to include library for function from JSON.stringify from
https://github.com/douglascrockford/JSON-js/blob/master/json2.js
hope this helps

Categories

Resources