Javascript get the name of the object after parsing from JSON - javascript

Consider the following JSON string:
[{"ElementID1":{"latitude":"10.02483","longitude":"70.753464"}},{"ElementID2":{"latitude":"10.029301","longitude":"70.751892"}},{"ElementID3":{"latitude":"10.029568","longitude":"70.751856"}}]
Which is contained in the "data" variable:
var response = JSON.parse(data);
How do I go through this result?
It is clear for me that I can access this first as an array:
for(var element in response)
{
}
But I don't know what "ElementID1" will be. It can be any string so i cant just do something like
element.elementID.latitude
To retrieve the object latitude. And i would also like to be able to get that picture id itself.
I think this is a simple question but i have tried googling for the answer for a while without any progress.

var data = [{"ElementID1":{"latitude":"10.02483","longitude":"70.753464"}},
{"ElementID2":{"latitude":"10.029301","longitude":"70.751892"}},
{"ElementID3":{"latitude":"10.029568","longitude":"70.751856"}}];
for(var i = 0; i < data.length; i++) {
var obj = data[i];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(obj[key].latitude);
}
}
}
DEMO
Basically, you need to access each data array element, which is an object in this case, and since you don't know the name of ElementID* for each element, you can loop through the properties of this object looking for the desired one, latitude in this case.

You can do the following:
response.forEach(function(response){
for (var element in response){
var picutureId = element;
var latitude = value[element].latitude;
var longitude = value[element].longitude;
// at this point you can manipulate the pictureId, latitude, and longitude of each object
}
})
Loop through the results array, loop through each object's key/val pair and manipulate the data from there.

If even latitude and longitude attribute names are unknown
for (var index in data) { //Iterate through array
var obj = data[index];
for (var prop in obj) { //Iterate through ElementId object
console.log(prop); //Print ElementID
var latlongObj = obj[prop];
for (var key in latlongObj) { //Iterate through latlong object
console.log(key); //Print lattitude/longitude
console.log(latlongObj[key]); //Print value
}
}
}

Related

Check json data for value and then get its key

I have some JSON data that I am retrieving from https://status.mojang.com/check and am storing in a variable. I'm still quite new to JSON/JS and I can't seem to find any answers on google.
Code:
function checkMojang() {
var mojangStatus = mojang.status();
mojangStatus.then(function (message) {
var response = JSON.parse(message);
})
}
Data I am using can be seen at the link above. I am trying to check all the data in the json array, see if any of the values contain "yellow" or "red" and get the keys for those values along with their checked value but can't figure out how to do so.
You can loop through the array and then through the object properties and make a new object using the colors as keys
var response = [{"minecraft.net":"green"},{"session.minecraft.net":"red"},{"account.mojang.com":"green"},{"auth.mojang.com":"green"},{"skins.minecraft.net":"green"},{"authserver.mojang.com":"yellow"},{"sessionserver.mojang.com":"green"},{"api.mojang.com":"green"},{"textures.minecraft.net":"green"},{"mojang.com":"red"}];
var new_response = {};
response.forEach(function(obj){
for (var prop in obj) {
if(obj.hasOwnProperty(prop)) {
if(new_response[obj[prop]] == undefined) new_response[obj[prop]] = [];
new_response[obj[prop]].push(prop);
}
}
})
console.log(new_response);
The you can use the object for your needs as
new_response["red"]
giving you the list of all key with red value.
you can use the method array.foreach() to execute a provided function once per array element and the for ... in to itarate over the enumarable properties.
So you can test the value and get keys for the value "yellow" or "red"
response.forEach(function(element) {
for (k in element) {
if (element[k]=="red" or element[k]=="yellow") {
// k is the key
}
}
});
function checkMojang() {
var mojangStatus = mojang.status();
mojangStatus.then(function (message) {
var response = JSON.parse(message);
for (i = 0; i < response.length; i++) { // iterate over response array
var item = response[i]; // get item from array
var key = Object.keys(item)[0]; // get the key of the item
var value = item[key]; // get the value of the item
if (value === 'yellow' || value === 'red') {
// do something, like adding it to a list
}
}
});
}

Map values from external json lookup into array as new key/value pairs

I am trying to map new values (from an external json file) into an array (array of arrays or KV pairs, generated from a php file query to mysql) in javascript/jQuery.
The structure of the array is:
"results":
[{"gender":"Male","DOB":"1993-09-22","location":"Main","procCode":"43653","preopDx1":"783.3","procedDate":"2008-06-02"},{"gender":"Female","DOB":"2001-11-07","location":"South","procCode":"11403","preopDx1":"216.5","procedDate":"2010-01-01"},...]
The json file looks like this:
[
{
"CPT": "10021",
"RVU": "1.27"
},
{
"CPT": "10022",
"RVU": "1.27"
}
]
The idea is to
a) Loop thru the myarray values and find each procCode
b) Match this procCode with the identical cpt code in the json file, and
c) Attach each new key/value pair to each 'row' of myarray
function addRVU (myarray, myjson){
var newObj = $.map(myarray, function (i,res){
if(myarray[i].procCode == myjson[i].CPT){
return myarray[i].RVU = myjson[i].RVU;
}
}
}
Thanks in advance!
// First, convert JSON file into an object keyed off CPT code:
var jsonObj = {};
for (var i = 0; i < json.length; i++) {
jsonObj[json[i].CPT] = json[i];
}
// Now update myarray elements
for (i = 0; i < myarray.length; i++) {
// $.extend copies properties from 2nd object into 1st object
$.extend(myarray[i], jsonObj[myarray[i].procCode]);
}
for if(myarray[i].procCode == myjson[i].CPT), you only matched the json and array with same index. loop to match all element in json should fix your problem.
or something like using a hash to map the RVU
h = {};
$.each(json, function(i, e){
h[e.CPT] = e.RVU;
});
$.each(ar, function(i, e){
e.RVU = h[e.procCode];
});

Manipulation of Javascript objects

I have an object in my javascript which looks like this:
{"data":[{"t":{
"level":"35",
"longtitude":"121.050321666667",
"latitude":"14.6215366666667",
"color":"#040098"}},
{"t":{
"level":"31",
"longtitude":"121.050316666667",
"latitude":"14.621545",
"color":"#040098"}},
{"t":{
"level":"29",
"longtitude":"121.050323333333",
"latitude":"14.62153",
"color":"#040098"}},
// .....
What I would like to do is to iterate thru the contents of my object so that I will be able to push them to their respective arrays independently.
I have an array for longitude, latitude, color and level.
So I have tried the following:
var size = 0, key;
for (key in result) {
if (result.hasOwnProperty(key)) size++;
alert(result.data[size]);
}
-->But this only alerts me "[object Object]"
success: function(result){
var size = 0, key;
for (key in result) {
for(var attr in key){
alert(attr['latitude']);
}
}
}
-->This gives me Undefined result[key]
I have checked that the size of my object is only 1 thru these codes
var size = 0, key;
for (key in result) {
if (result.hasOwnProperty(key)) size++;
}
alert(size);
I believe that only "data" is being read. And others that are inside "data" are disregarded.
I have read this, this, enter link description here, and this but they sall seem to deal with a different structure of objects. Thanks for the help in advanced.
UPDATE
Using the console.log(), I have confirmed, if im not mistaken that only the first attribute is being fetched
t
Object { level="35", longtitude="121.0508", latitude="14.6204083333333", more...}
color "#040098"
latitude "14.6204083333333"
level "35"
longtitude "121.0508"
I tried this
for (key in result) {
if (result.hasOwnProperty(key)) size++;
console.log(result.data[size]['level']);
}
--> but it says undefined
based on the structure of my object which is
data:[{"t":{'others'},'others'...]
How am I to read everything inside "data"? Each "data" has "t".
Update: Using the for...in construct for iterating over arrays isn't recommended. The alternative is a regular for loop (each method of course having their respective advantages):
for(var i=0; i<results.data.length; i++){
alert(results.data[i]['t']['latitude']);
// etc...
}
Be careful with the structure of your JSON. Also note that the javascript foreach loop iterates over keys/indices -- not values. See demo: http://jsfiddle.net/g76tN/
success: function(result){
var latitudes = [];
// and so on...
for (var idx in result.data ) {
if( result.data.hasOwnProperty(idx) ){
alert( result.data[idx]['t']['latitude'] );
// So you would do something like this:
latitudes.push ( result.data[idx]['t']['latitude'] );
// and so on...
}
}
}​
Note for collecting properties of objects in an array, jQuery $.map() -- or native js array map for that matter -- is a neat, useful alternative.
var latitudes = $.map( result.data, function(n){
return n['t']['latitude'];
});
// and so on...
Assuming result is your object, this should just be a matter of iterating over your data array:
for (var i = 0; i < result.data.length; ++i) {
console.log(result.data[i].t.latitude);
...
}
It's not hard to do, as shown below. But why would you want to take useful objects like your t's and turn them into such arrays?
var levels = [], longitudes= [], latitudes = [], colors = [];
var result = {"data":[{"t":{
"level":"35",
"longtitude":"121.050321666667",
"latitude":"14.6215366666667",
"color":"#040098"}},
{"t":{
"level":"31",
"longtitude":"121.050316666667",
"latitude":"14.621545",
"color":"#040098"}},
{"t":{
"level":"29",
"longtitude":"121.050323333333",
"latitude":"14.62153",
"color":"#040098"}}
]};
var data = result.data;
var i, len, t;
for (i = 0, len = data.length; i < len; i++) {
t = data[length].t;
levels[i] = t.level;
longitudes[i] = t.longtitude;
latitudes[i] = t.latitude;
colors[i] = t.color;
}
See http://jsfiddle.net/VGmee/, which keeps the hasOWnProperty (which is important), and your misspelling of "longitude", which is not.
var data = input.data,
result = {level: [], longtitude: [], latitude: [], color: []};
for (var i = 0, n = data.length; i < n; i += 1) {
var info = data[i].t;
for (var property in info) {
if (info.hasOwnProperty(property)) {
result[property].push(info[property]);
}
}
}
console.log(result.level);
console.log(result.latitude);
console.log(result.longtitude);
console.log(result.color);
This requires the result arrays to actually have the properties in your input array, but you can add error handling as desired.

Get Length of json Data

i have this json data and i want to get length of this json data and also of css
my json data is shown here
jso({tag:"div",css:{backgroundColor:"red"},html:"abc"})
i have pass this in function
function jso(data){
alert(data.length)
}
Your JSON is not a valid JSON object
{
"tag": "div",
"css": {
"backgroundColor":"red"
},
"html":"abc"
}
However proper JSON object don't have a length attribute, so you need to iterate over them to calculate the length.
i know what u mean u just need to loop over your object with a counter variable
var x = {tag:"div",css:{backgroundColor:"red"},html:"abc"}
function objectLength(obj){
var counter = 0;
for(var i in obj)
{
counter +=1;
}
return counter
}
use it like this
alert(objectLength(x))
To iterate over the data using jQuery counting how many iterations you did do the following:
var data = {tag:"div",css:{backgroundColor:"red"},html:"abc"};
var count = 0;
$.each(data, function(key, value) {
count++;
});
See jsFiddle here.
To iterate over the data using JavaScript only counting how many iterations you did do the following:
var data = {tag:"div",css:{backgroundColor:"red"},html:"abc"};
var count = 0;
var key;
for(key in data)
{
var value = data[key];
count++;
}
​See jsFiddle here.

How to parse JSON data when the property name is not known in advance?

Here is my response code in jQuery:
var response = $.parseJSON(response);
for (var i = 0; i < response.groupIds.length; i++) {
console.log(response.groupIds[i], i);
}
Each response.groupIds[i] is of the form {"unknown name":"unknown value"}.
I wish to access both of these bits of data in javascript, how do I accomplish this when I don't know in advance what e.g. unknown name is?
Use Object.keys to retrieve a full list (array) of key names. A polyfill is available here.
var group = response.groupIds[i];
var allPropertyNames = Object.keys(group);
for (var j=0; j<allPropertyNames.length; j++) {
var name = allPropertyNames[j];
var value = group[name];
// Do something
}
Your question's response format contains only one key-value pair. The code can then be reduced to:
var group = response.groupIds[i];
var name = Object.keys(group)[0]; // Get the first item of the list; = key name
var value = group[name];
If you're not interested in the list, use a for-i-in loop with hasOwnProperty. The last method has to be used, to exclude properties which are inherit from the prototype.
for (var name in group) {
if (group.hasOwnProperty(name)) {
var value = group[name];
// Do something
}
}
Use a for..in loop:
for( x in response.groupIds[i]) {
// x is now your unknown key
// response.groupIds[i][x] is the unknown value
}
Since there is only one property of the object, that'll work nicely.

Categories