Access JSON key value dynamically using jquery - javascript

Below is my json which is dynamic. I want to access 'bf' key in the json , 'xxxxxx20160929' and 'yyy813AI20160929' keys are dynamic but json structure will be the same
{
"resultData": [
{
"a": "124",
"b": "0",
"c": "0",
"flc_schedu": {
"e": "6",
"f": "en",
"xxxxxx20160929": [
{"ID": "yyyyyyyy" },
{"ID": "fffff"}
]
},
"fareDetails": {
"xxxxxx20160929": {
"yyy813AI20160929": {
"O": {
"AD": {
"bf": "2527"
}
}
}
}
}
}
]
}
Below is how I tried
response.resultData[0].fareDetails[Object.keys(response.resultData[0].fareDetails)[0]]
If I try as above I can able to access dynamically up to "xxxxxx20160929" key, but I can't able get how to reach up to "bf" key dynamicaly.

You can reference an object using the array syntax.
var one = 'xxxxxx20160929';
var two = 'yyy813AI20160929';
data.resultData[0].fareDetails[one][two].O.AD.bf;
UPDATE:
This code assumes there is only one dynamic object at each layer.
var one = Object.keys(data.resultData[0].fareDetails)[0];
var two = Object.keys(data.resultData[0].fareDetails[one])[0];
var thing = data.resultData[0].fareDetails[one][two].O.AD.bf;

function getBFFromFareDetails(details){
var bfValues = [];
for(var k in details.fareDetails){
// loop over the children of fareDetails
if( details.fareDetails.hasOwnProperty( k ) ) {
//each entry in ;fareDetails'
var itemRoot = details.fareDetails[k]
for(var k1 in itemRoot){
// loop over the children of the first unknown item
if( itemRoot.hasOwnProperty( k1 ) ) {
//return the bf from the first unknown child
return itemRoot[k1].O.AD.bf;
}
}
}
}
}
If you call this with var bf = getBFFromFareDetails(response.resultData[0])
this will return the value for the first bf in the first child of fareDetails and its first child.
You can see a quick example in action here https://jsfiddle.net/tocsoft/5364x2sp/

If you are able to access up to "xxxxxx20160929" level then create a var to store that level, then use that variable to access the next which you will need to store in a variable, then use both variable to access the key needed.
var1 = response.resultData[0].fareDetails)[0];
var2 = response.resultData[0].fareDetails)[0][var1];
response.resultData[0].fareDetails)[0][var1][var2];

Related

How to get object name data list with where condition in Javascript?

I want get spesific data form my name object jumlahproduksi data but i got a problem not working with i tried this code.
I use grep function because need where condition base city(lokasi)
var e = 0;
while (e < kota.length) {
var filtered = $.grep(data, function (el) {
return el.lokasi == kota[e];
});
console.log(filtered);
e = e+1;
}
I have data like this:
my data
I want the data model like this: Show jumlahproduksi
model data i want
So Appreciate your help. Thanks
Pro-itp: Don't use jQuery's grep to search through JSON because you cannot meaningfully extract data from JSON in all circumstances using a Regular Expression because JSON is not a Regular Language.
Moving on, just use JSON the way it's intended to be consumed: as native JS objects. You can use Array.map to apply a projection to an input array, like so:
var jsonInput = `[
{ "tahun": "2015", "lokasi": "Kab. Benhulu Seltan", "jumlahproduksi": "0" },
{ "tahun": "2016", "lokasi": "Kab. Benhulu Seltan", "jumlahproduksi": "0" },
{ "tahun": "2017", "lokasi": "Kab. Benhulu Seltan", "jumlahproduksi": "9795" }
]`;
var root = JSON.parse( jsonInput );
var values = root.map( e => e.jumlahproduksi );
console.log( values ); // [ "0", "0", "9795" ]
Here's a JSFiddle demo: https://jsfiddle.net/60ncb3g1/

How to get values in Json Array and use each of them separately

I have a JSON and I Want to separate each field of that in array part and then I want to use of each field separately and put them in separate array.
for example I have two part in my array and I want to divide the first part too room 1 and second part in room 2 .
I have to send Json to my second page with format room1 and room 2. and I do not know how can I do this
my json is like this right now :
"rooms": [
{
"adultcount": "1",
"childcount": "1,1"
},
{
"adultcount": "1",
"childcountandage": "0 "
}
]
but I want to change it like this :
"rooms": [
{
"rooms1": {
"adultcount": "1",
"childcount": "1,1"
}
},
{
"rooms2": {
"adultcount": "2",
"childcount": "10,1"
}
}
]
then I need to use them.
how can I do this with jquery ?
there is no need to change the json code I just wrote the sample the new json to define better.
here is my code :
$( document ).ready(function() {
var research={"rooms":[{ "adultcount":"1","childcount":"1,1" },{ "adultcount":"1","childcountandage":"0 " }] }
var adultcount = research.rooms[0].adultcount;
var childcount = research.rooms[0].childcount;
});
Since you have an array that you want to make into an object and the property name seems to be the index inside the array, you can use a basic array.reduce:
var rooms = [
{ "adultcount":"1", "childcount":"1,1" },
{ "adultcount":"2", "childcount":"10,1" }
];
var roomsMap = rooms.reduce( function( map, room, index ) {
map[ 'room' + ( index + 1 ) ] = room;
return map;
}, {} );
var otherRoomsMap = rooms.map( function( room, index ) {
var wrapper = {};
wrapper[ 'room' + ( index + 1 ) ] = room;
return wrapper;
} );
console.log( roomsMap );
console.log( otherRoomsMap );
edit:
I have added the other example of keeping the array and just wrapping the objects isnide another object, but I have no idea what advantage that would give over the original array.
You can access your json array using loop
$.each(research, function (key, value) {
var adultcount = value.adultcount;
var childcount = value.childcount;
console.log("Adult count is:"+value.adultcount);
console.log("Child count is:"+value.childcount);
});
Try this:
var research={"rooms":[{ "adultcount":"1","childcount":"1,1" },{"adultcount":"1","childcountandage":"0 " }] };
var newResearch = {"rooms": []};
research.rooms.forEach(function(r) {
newResearch.rooms.push({"room1": r[0], "room2": r[1]});
});
console.log(newResearch);

how to read json data if name and value is unknown and there length also

I have to create json dynamically, which is not a problem but in one place json name and value pair are random and can also be different, so is it possible to read json.
var json = {
"set":[
{
"name":"Device 1",
"children":[
{
"name":"name",
"name1":"name",
"xyz":"hello",
"abc":"hello1",
"vwx":"hello2",
"stu":"hello3",
"children":[
{
"type1":"iname",
"type2":"cname",
"type3":"pname"
}
]
}
]
},{
"name":"Device 2",
"children":[
{
"name":"name3",
"name4":"name4",
"def":"hello2",
"lmn":"hello3",
"children":[
{
"type1":"iname",
"type2":"cname",
"type3":"pname"
}
]
}
]
}
]};
This is a part I have done to iterate data before children.But as my doubt was only for data between children that's why I have shorten the json to only limit it to the question I have asked
$(window).bind("load", function() {
var mouseX;
var mouseY;
$(document).mousemove( function(e) {
mouseX = e.pageX;
mouseY = e.pageY;
});
$.each(device_json.device, function(i, v) {
$('#front'+v.position).append(v.name);
$('#front'+v.position).hover(function(){
$('#front'+v.position).append('<div class="hover"><b>Name :</b> ' +v.name+'</div>').css({'cursor':'pointer'}).show();
$('.hover').css({'top':mouseY,'left':mouseX});
},function(){
$('.hover').remove();
});
I have to show the data between children in table form first td will be name and second will show value, but how many are there in between children is unknown and also there sequence is not same.Any help will be appreciated.Thanks in advance
"children" is an array of objects, you could loop on these objects properties. Here is a way of doing that:
for (var i = 0, keys = Object.keys(object), l = keys.length; i < l; ++i){
propertyValue = object[keys[i]];
}
You can find others at https://jsperf.com/iterating-over-object-properties/2
Then you could test the name of the property, to see if it is a "children" array, or something else.
If you have access to what is creating this json, maybe you can also change its organization to avoid your issue.

Iterate JSON array with maps using jquery

Below is the JSON array i am receiving from the dynamo DB and i need to iterate the same display the results in a table. where M is Map with more than one values. Can any one help me with the Jquery and HTML part of it.
{
"Item": {
"Subscriptions": {
"M": {}
},
"NetworkID": {
"S": "1234"
},
"SubscriptionARNs": {
"SS": [
" "
]
}
}
}
Here is all the data in details you can do what you want to do with it, first one deal with it as a hash, second as a string, third as an array:
data = {....}
item = data["Item"]
Subscriptions = item["Subscriptions"]
NetworkID = item["NetworkID"]
SubscriptionARNs = item["SubscriptionARNs"]
// for Subscriptions Data
M = Subscriptions["M"]
keys = Object.keys(M)
for(i = 0;i<keys.length;i++){
console.log(keys[i] +"="+M[keys[i]])
}
// for Network Data
S = NetworkID["S"]
// for SubscriptionARNs Data
SS = SubscriptionARNs["SS"]
for(i = 0;i<SS.length;i++){
console.log(SS[i])
}

How to navigate in nested JSON

I have nested JSON object like
{"baseball":
{"mlb":
{"regular":
{"_events": [{"start_time": "2011-07-31 17:35", "lines":
[{"comment": "", "coeff": "2.35", "title": "2", "old_coeff": "2.35", "is_main": true},
{"comment": "", "coeff": "1.59", "title": "2", "old_coeff": "1.59", "is_main": true},
{"comment": "", "coeff": "1.59", "title": "2", "old_coeff": "1.59", "is_main": true},
{"comment": "", "coeff": "2.35", "title": "2", "old_coeff": "2.35", "is_main": true}],
"members": ["atlanta", "florida"]
}
]
}}}}
And i need get _events array and parse it too. But I don't know what will be in cells before _events and how they will. How do I work with this structure?
function recursiveGetProperty(obj, lookup, callback) {
for (property in obj) {
if (property == lookup) {
callback(obj[property]);
} else if (obj[property] instanceof Object) {
recursiveGetProperty(obj[property], lookup, callback);
}
}
}
And just use it like this:
recursiveGetProperty(yourObject, '_events', function(obj) {
// do something with it.
});
Here's a working jsFiddle: http://jsfiddle.net/ErHng/ (note: it outputs to the console, so you need to Ctrl+Shift+J/Cmnd+Option+I in chrome or open firebug in Firefox and then re-run it)
If the structure is known:
Assuming that you have the above in a String called input (and that the JSON is valid):
var obj = JSON.parse(input) // converts it to a JS native object.
// you can descend into the new object this way:
var obj.baseball.mlb.regular._events
As a warning, earlier versions of IE do not have JSON.parse, so you will need to use a framework for that.
If the structure is unknown:
// find the _events key
var tmp = input.substr(input.indexOf("_events"))
// grab the maximum array contents.
tmp = tmp.substring( tmp.indexOf( "[" ), tmp.indexOf( "]" ) + 1 );
// now we have to search the array
var len = tmp.length;
var count = 0;
for( var i = 0; i < len; i++ )
{
var chr = tmp.charAt(i)
// every time an array opens, increment
if( chr == '[' ) count++;
// every time one closes decrement
else if( chr == ']' ) count--;
// if all arrays are closed, you have a complete set
if( count == 0 ) break;
}
var events = JSON.parse( tmp.substr( 0, i + 1 ) );
The easiest thing to do in this situation, I find, is to go to JSFiddle, paste in your json as a variable:
var json = {"baseball": ... etc.
console.log(json);
Then using Chrome, "View" -> "Developer" -> "Javascript console" start to experiment with what the data structure looks like in order to build up your parsing function.
Then start experimenting with the structure. Eg.
console.log(json.baseball.mlb.regular._events);
Or if you turn on JQuery:
$.each(json.baseball.mlb.regular._events, function(i, item){
$.each(item.lines,function(i,line){
console.log(line.coeff);
});
});
If you're having trouble actually loading in this JSON into a variable you'll need to JSON.parse a string retrieved via an AJAX call I suspect.

Categories

Resources