how to browse a javascript object - javascript

I'm new to jQuery. Following is the data variable that contains a json dictionary.
{
"user":null,
"currency":"EUR",
"balance":0,
"translist": [
{ "trans1":"something","trans2":"something2" }
]
}
and my jQuery method receives a json/Javascript object from the Rest GET call
success: function (data){
for(x in data) {
console.log(x + ': ' + data[x]);
}
});
Is there any library that can help to parse/walk through this json object and get to some kind of objects list? I want to check some of the keys and their respective values. Problem is I don't need all the keys and values from the list and also some of the values can be null, which prevented me to apply some solutions I found using SO.
Or usually is it more common to directly start printing the HTML inside the success function?
EDIT:If it was java for example it would be a Map and I would use an iterator to walk through and see/analyse the map values, and create some array list with the values I want from it. What's equivalent of that in jQuery?

If it was java for example it would be a Map and I would use an
iterator to walk through and see/analyse the map values, and create
some arraylist with the values I want in it. What is the equivalent of that
in jQuery?
Any javascript object can be seen as an associative map.
You can for example directly access the currency as data['currency'].
You can also build an array :
var a = [];
for (var key in data) {
a.push({key:key, value:data[key]});
}
You could also build some HTML and apply functions to the data :
$(document.body).append($(
'<table>' + a.map(function(v){
return '<tr><td>'+v.key+'</td><td>'+v.value+'</td></tr>'
}).join('')+'</table>'
));
Demonstration
Using jQuery can make the same iteration simpler (working directly from data) :
$(document.body).append($(
'<table>' + $.map(data, function(value,key){
return '<tr><td>'+key+'</td><td>'+value+'</td></tr>'
}).join('')+'</table>'
));
Demonstration

Try using each
success: function (data){
$.each( data, function( key, value ) {
if(key === "currency")
alert( key + ": " + value );
});
});

Related

What is the correct way to handle this data using jQuery?

I have a list of html elements with data attributes, which I would like to assemble into a jQuery object and manipulate the values.
What is the best way to dynamically add these in an each loop so that I can easily access the data as so: data.name and data.name.prop?
I want all the naming conventions to be dynamic and based on the data.
I based my code on the top answer from here: How to create dynamically named JavaScript object properties?
So far I have:
$('.licences-list .data div').each(function(index) {
var data = {}
cats[$(this).find('p').data('cat')] = $(this).find('p').data('catname')
cats.push(data)
})
But when I try to iterate over the data array, like so:
$.each(cats, function(key, value){
$('<div class="card"><p>'+value+'</p></div>').appendTo('#commercial-licenses');
});
I just get [object Object] output... and I'm not sure why!
var data = {}
cats[$(this).find('p').data('cat')] = $(this).find('p').data('catname')
Each time you loop through, you're actually just adding an empty object (data) to your array (cats). You're then assigning a named property to that array (cats) which $.each has no idea about (it ignores them because it's iterating over an actual array).
My guess is you want an object map which is something like: var cats = { "f1": "feline 1", "f2": "feline " };
In that case what you want is:
var cats = {};
$('.licences-list .data div').each(function(index) {
cats[$(this).find('p').data('cat')] = $(this).find('p').data('catname')
})
If you want an array that contain more values than just strings (or whatever data you have added to the element), you create new objects each time and append them to the cats array:
var cats = [];
$('.licences-list .data div').each(function(index) {
cats.push({
'id': $(this).find('p').data('cat'),
'name': $(this).find('p').data('catname')
});
})
This will then give you an array that you can use $.each over, and access the values using: value.id, value.name
Don't over complicate it.
$('.div').attr('data-attribute', 'data-value');
using your example:
$('.licences-list .data div').attr('attribute-name', 'attribute-value');

display specific object values in an array instead of individually?

I have used an ajax call to retrieve data from Googles places api and I have used a for/in loop to begin to pull the information. the information that I am looking for logs to the console, but I cannot get it to display in an array how I would like it to.
Right now I am getting a list of names when I request names which is a parameter in the JSON object. Is there a way to get it into an array so the I can randomly select one of the values from the array?
at this point the way it is returning my data, when I run a script to pull a random string, it pulls a random letter out of the last value to be found when searching through my JSON object.
Here is my code. Not sure if I explained myself clearly but it's the best that I could word what I am looking to do. Thanks.
// **GLOBAL VARIABLES** //
// Chosen Restaurant display area
var display = document.getElementById('chosenVenue');
// Grab button
var button = document.getElementById('selectVenue');
// Sample Array that gets queried
var venueData = ["McDonalds", "Burger King", "Wendys"];
// Grab JSON data from Google
$(document).ready(function(){
$.ajax({
url: 'hungr.php', // Send query through proxy (JSONP is disabled for Google maps)
data: { requrl: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.7484,-73.9857&radius=800&sensor=false&keyword=restaurants,food&key=AIzaSyBkCkXIHFjvqcqrRytSqD7T_RyFMNkR6bA&callback=?"}, // URL to query WITH parameters
dataType: "json",
type: "GET", // or POST if you want => update php in that case
success: function (data) {
// Traverse the array using for/in loop using i as var
for (var i in data.results) {
var results = data.results[i];
var nameResults = results.name;
console.log(nameResults);
var typesResults = results.types;
console.log(typesResults);
var vicinityResults = results.vicinity;
console.log(vicinityResults);
};
// On button click, randomly display item from selected array
button.addEventListener('click', function () {
console.log('clicked');
display.style.display = 'block';
//display.innerHTML = nameResults[Math.floor(Math.random() * nameResults.length)];
display.innerHTML = nameResults.toString() + "<br />" + vicinityResults.toString();
});
console.log('It is working');
},
error: function (request, status, error) {
console.log('It is not working');
}
});
});
Right now I am getting a list of names when I request names which is a parameter in the JSON object. Is there a way to get it into an array so the I can randomly select one of the values from the array?
Use the push method and a non-local variable:
this.nameResults = this.nameResults ? this.nameResults.push(results.name) : [];
then reference that with the Math.random method:
this.randName = function(){ return this.nameResults[Math.random() * this.nameResults.length | 0] };
References
Using Math.random flexibly
JavaScript: fast floor of numeric values using the tilde operator

extract single variable from JSON array

I hope my question is not as stupid as I think it is...
I want to extract (the value of) a single variable from an JSONarray. I have this jquery code
$(document).ready(function(){
$("#gb_form").submit(function(e){
e.preventDefault();
$.post("guestbook1.php",$("#gb_form").serialize(),function(data){
if(data !== false) {
var entry = data;
$('.entries').prepend(entry);
}
});
});
});
the content of data looks like this ("MyMessage" and "MyName" are values written in a simple form from user):
[{"message":"MyMessage","name":"MyName"}]
the var "entry" should give (more or less) following output at the end:
"Send from -MyName- : -MyMessage-"
I'm not able to extract the single array values from data. I tried things like that:
var message = data['message'];
var name = data['name']
var entry = "Send from" + name + ":" +message;
but that gives "Send from undefined: undefined"
Hope you can help me with that.
you can do like this to get first item of array:
var msg = "Send from"+data[0].name + " "+data[0].message;
console.log(msg );
SAMPLE FIDDLE
UPDATE:
as you are using $.post you will need to explicitly parse response as json:
$.post("guestbook1.php",$("#gb_form").serialize(),function(data){
var response = jQuery.parseJSON(data);
var msg = "Send from"+response [0].name + " "+response [0].message;
console.log(msg );
});
To access an array you use the [] notation
To access an object you use the . notation
So in case of [{JSON_OBJECT}, {JSON_OBJECT}]
if we have the above array of JSON objects in a variable called data, you will first need to access a particular Json Object in the array:
data[0] // First JSON Object in array
data[1] // Second JSON Object in array.. and so on
Then to access the properties of the JSON Object we need to do it like so:
data[0].name // Will return the value of the `name` property from the first JSON Object inside the data array
data[1].name // Will return the value of the `name` property from the second JSON Object inside the data array

How to Access Array response of AJAX

This is my AJAX call response which is in array format
[1,2,3,4,5,6]
success: function(outputfromserver) {
$.each(outputfromserver, function(index, el)
{
});
How can we access outputfromserver all values ??
Means outputfromserver Zeroth value is 1 , 2nd element is 2 , -----so on
It would help to know what your AJAX request looks like. I recommend using $.ajax() and specifying the dataType as JSON, or using $.getJSON().
Here is an example that demonstrates $.ajax() and shows you how to access the returned values in an array.
$.ajax({
url: 'test.json', // returns "[1,2,3,4,5,6]"
dataType: 'json', // jQuery will parse the response as JSON
success: function (outputfromserver) {
// outputfromserver is an array in this case
// just access it like one
alert(outputfromserver[0]); // alert the 0th value
// let's iterate through the returned values
// for loops are good for that, $.each() is fine too
// but unnecessary here
for (var i = 0; i < outputfromserver.length; i++) {
// outputfromserver[i] can be used to get each value
}
}
});
Now, if you insist on using $.each, the following will work for the success option.
success: function (outputfromserver) {
$.each(outputfromserver, function(index, el) {
// index is your 0-based array index
// el is your value
// for example
alert("element at " + index + ": " + el); // will alert each value
});
}
Feel free to ask any questions!
The array is a valid JSON string, you need to parse it using JSON parser.
success: function(outputfromserver) {
var data = JSON.parse(outputfromserver);
$.each(data, function(index, el) {
// Do your stuff
});
},
...
You can use JS objects like arrays
For example this way:
// Loop through all values in outputfromserver
for (var index in outputfromserver) {
// Show value in alert dialog:
alert( outputfromserver[index] );
}
This way you can get values at first dimension of array,
above for..loop will get values like this:
// Sample values in array, case: Indexed array
outputfromserver[0];
outputfromserver[1];
outputfromserver[2];
// So on until end of world... or end of array.. whichever comes first.
outputfromserver[...];
However, when implemented this way, by using for ( index in array ) we not only grab indexed 1,2,3,4,... keys but also values associated with named index:
// Sample values in array, case: accosiated/mixed array
outputfromserver["name"];
outputfromserver["phone"];
outputfromserver[37];
outputfromserver[37];
outputfromserver["myindex"];
// So on until end of world... or end of array.. whichever comes first.
outputfromserver[...];
In short, array can contain indexed values and/or name associated values, that does not matter, every value in array is still processed.
If you are using multidimensional stuff
then you can add nested for (...) loops or make recursive function to loop through all and every value.
Multidimensional will be something like this:
// Sample values in array, case: indexed multidimensional array
outputfromserver[0][0];
outputfromserver[0][1];
outputfromserver[1][0];
outputfromserver[1][...];
outputfromserver[...][...];
Update, JSON object:
If you server returns JSON encoded string you can convert it to javascript object this way:
try {
// Try to convert JSON string with jQuery:
serveroutputobject = $.parseJSON(outputfromserver);
} catch (e) {
// Conversion failed, result is not JSON encoded string
serveroutputobject = null;
}
// Check if object converted successfully:
if ( serveroutputobject !== null ) {
// Loop through all values in outputfromserver
for (var index in serveroutputobject) {
// Append value inside <div id="results">:
$('#results').append( serveroutputobject[index] + "<br/>" );
}
}
// In my own projects I also use this part if server can return normal text too:
// This way if server returned array we parse it and if server returns text we display it.
else {
$('#results').html( outputfromserver );
}
More information here
$.ajax({
type : "POST",
dataType: "json",
url : url,
data:dataString,
success: function(return_data,textStatus) {
temperature.innerText=return_data.temp;
// OR
**temperature.innerText=return_data['temp'];**
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error while accessing api [ "+url+"<br>"+textStatus+","+errorThrown+" ]"); return false;
}
});

How do I iterate over object literal array with jquery $.each() method?

how do I iterate over object literal array with jquery $.each() method?
In the chrome debugger, it comes back as "undefined, undefined".
Any help would be really appreciated. thanks!
var links = [
{ className : 'hover', url : 'http://www.yahoo.com' },
{ className : 'hover-2', url : 'http://www.foxnews.com' },
];
loopy(links)
function loopy(obj){
$.each(
obj,
function(){
console.log(obj.className + ', ' + obj.url);
}
);
}
Try:
$.each(
obj,
function(i, val){
console.log(val.className + ', ' + val.url);
}
);
The $.each function parameter takes two arguments -- the index of the current item in the array, and the second is the actual current value of the array.
See the API for some more explanation and examples.
You can see this fiddle to see it in action.
I just wanted to offer a slightly modified version of David's response that will be a little more gentle on the DOM when processing larger objects.
Original answer (above):
$.each(
obj,
function(i, val){
console.log(val.className + ', ' + val.url);
}
);
This solution works, but it generates an entirely new instance of the iterator function for every property in the object. There's no need for that, and I think you'll find more stable performance in larger applications by declaring specific methods to handle that sort of thing.
Try this:
// Process a property in your link object
function links_iterationHandler(i, val) {
console.log(val.className + ', ' + val.url);
}
// Traverse the link object and pass each result off to the method above
$.each(obj, links_iterationHandler);
This essentially does the same thing, but doesn't hammer on the DOM as much. It's not a big deal if you only have a few items in your object. But if you're dealing with a lot of data, like a big recordset loaded via Ajax, it will make a difference for sure.
Cheers!
I would try this:
$.each([52, 97], function(index, value) {
alert(index + ': ' + value);
});
The first property is the index.
http://api.jquery.com/jQuery.each/

Categories

Resources