How to print out object properties within for-in loop? - javascript

I'm getting a list of objects from an API which looks like this:
{
"results": [
{
"date": "2014-09-25 19:00:00",
"title": "Hitjeskanon"
},
{
"date": "2014-09-25 21:00:00",
"title": "Black & White ESN House & Techno"
},
{
"date": "2014-09-25 21:00:00",
"title": "Hit It!"
}
]
}
I now get these results from the API, and want to log them, which I try as follows:
$.ajax({
url: "/eventSearch/" + q,
cache: false,
success: function(result) {
console.log(result);
console.log(result['results']);
for (event in result['results']) {
console.log(event['title']);
}
}
});
In the console, I correctly see the objects with the first two logs, but the console.log(event['title']) only prints out undefined.
What am I doing wrong here? All tips are welcome!

result['results'] is actually an Array. So, you should iterate it with normal for loop like this
for (var i = 0; i < result['results'].length; i += 1) {
console.log(result['results'][i]['title']);
}
Or you can use Array.prototype.forEach like this
result['results'].forEach(function(currentObject) {
console.log(currentObject['title']);
});
Also, you can access the attributes with the dot operator, like this
console.log(result.results[i].title);
or
console.log(currentObject.title);

You could use a traditional for loop, but if you don't need random access (e.g., results[2]) you can use a for...of statement (introduced in ECMAScript6). In your code, just change for...in to for...of:
$.ajax({
url: "/eventSearch/" + q,
cache: false,
success: function(result) {
console.log(result);
console.log(result['results']);
for (event of result['results']) {
console.log(event['title']);
}
}
});
And like #thefourtheye mentioned, you can access the results array and the event's title property with the dot operator:
$.ajax({
url: "/eventSearch/" + q,
cache: false,
success: function(result) {
console.log(result);
console.log(result.results);
for (event of result.results) {
console.log(event.title);
}
}
});
This page is a great reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

Related

How do I place a json value using jquery?

I am sending selected fields to an API(3rd party app) from wordpress.
This is how my data array looks like:
var data_array = {
"order": {
"customer": {
"name": "The User"
}
}
}
I want to substitute the value of the "name" key to a javascript variable that contains a jquery selector. For example:
var name = j('.billing_company_name').html(result.meta_data[1].value);
I am thinking that the new code for the data_array will be:
var data_array = {
"order": {
"customer": {
"name": name(variable name jquery selector)
}
}
}
Do you know the correct syntax so I can substitute the value of "name" key with the value of the jquery selector?
The final code will look like the code below:
j.ajax({
type: 'POST',
url: 'http://mywebsite/api/orderdetails',
cache: false,
data: {
"data_array": data_array
},
beforeSend: function() {
},
success: function(result) {
},
error: function(xhr, status, error) {
console.log(error);
},
complete: function() {
}
});
I need the value of the element to be place inside the value of data_array.order.customer.name
In this case you can use val() to select that property. If you want to do it as you instantiate the object, use this:
var data_array = {
"order": {
"customer": {
"name": name.val()
}
}
}
Or if you want to do it after declaring data_array (which is badly named, as it's an object not an array), then you can use this line:
data_array.order.customer.name = name.val();

extract an URL from a JSON response of wikipedia api

I need to extract the URL of an image from a JSON response (maybe I could put it in a variable).
I read this page on the MediaWiki API help
I follow this example to get the information about images on a page:
https://commons.wikimedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100
that return this JSON:
{
"batchcomplete": "",
"query": {
"pages": {
"2061": {
"pageid": 2061,
"ns": 0,
"title": "Albert Einstein",
"thumbnail": {
"source": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Albert_Einstein_Head.jpg/75px-Albert_Einstein_Head.jpg",
"width": 75,
"height": 100
},
"pageimage": "Albert_Einstein_Head.jpg"
}
}
}
In which way can I extract the URL of the image?
I tried this:
$.ajax({
type:"get",
url:"https://commons.wikimedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100&format=json",
dataType:"jsonp",
contentType:"application/json; charset=utf-8",
success: function(data) {
var urlImage = data.query.pages.2061.thumbnail.source;
var stgurl = JSON.stringify(urlImage);
alert(stg);
}
})
but doesn't work.
Yes, it doesn't work because this url: https://commons.wikimedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100 doesn't return JSON but HTML. If you want the JSON representation, you need to append &format=json to your url.
Change data.query.pages.2061.thumbnail.source to data.query.pages["2061"].thumbnail.source as you can't use numbers in a dot notation.
And also the alert; change stg to stgurl
$.ajax({
type:"get",
url:"https://commons.wikimedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100&format=json",
dataType:"jsonp",
contentType:"application/json; charset=utf-8",
success: function(data) {
var urlImage = data.query.pages["2061"].thumbnail.source;
//var stgurl = JSON.stringify(urlImage); - unnecessary JSON.stringify
var stgurl = urlImage;
alert(stgurl);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I tried to use the solution in this post:
iterating through json object javascript
Use the recursion in this way:
function walk(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
walk(val);
}
}
}
walk(obj);
it seems to work.

How would I sort list items that I am getting from a document library with javascript?

Currently I have some JavaScript that retrieves list items and displays them as part of an unordered list. I've been given the task of modifying the javascript below to sort items.
<script type="text/javascript" defer="defer">
$.ajax({
url: "/NewsEvents/_api/web/lists/GetByTitle('Newsletters')/items?$select=Title,FileRef",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (data) {
returnedvalue = data;
var count = 0;
$.each(data.d.results, function (index, item) {
$('#NL ul').append("<li>" + "<a href='" + item.FileRef + "'>" + item.Title + "</a>" + "</li>");
count++;
});
},
error: function (error) {
alert(JSON.stringify(error));
}
});
</script>
I haven't done much javascript before and am willing to learn. Would love to be pointed in the right direction rather than just given an answer.
I'm assuming that data.d.results is a JavaScript array that resembles the following example:
results: [
{
Title: "Article Title",
FileRef: "something/or/other"
},
{
Title: "Another Article Title",
FileRef: "something/or/other/again"
},
]
JavaScript's Array type has a built-in sort method, which accepts a custom comparator ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort ).
I use the localeCompare ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare ) method to compare the Title values of each array element.
I specify sensitivity: "base" to perform a case and and accent invariant comparison, so "article" and "Article" are considered equal when compared.
success: function( data ) {
data.d.results.sort(
function( left, right ) {
return left.Title.localeCompare( right.Title, { sensitivity: "base" } );
}
);
// rest of your code here
}

Parsing JSONP file with JavaScript

How do I access the Marie-Antoinette.json object in this JSON file? I would like to get the title element of the object but I can't seem to get it to output. Here is my JavaScript code which outputs the object but I cant seem to access the objects elements.
$.ajax(
{
type: 'GET',
url: 'http://localhost:5984/movies/efadd5913f5cfd254b2861efd4001cb7',
//contentType: "application/json; charset=utf-8",
dataType: "JSONP",
jsonpCallback: 'callback',
//async: false,
success: function(r)
{
alert("ok");
$.each(r, function(index, value){ // iterating over each object
console.log(index);
if(index == "_attachments")
{
console.log(value); //how do I output the title ("Marie-Antoinette.json") and the other stuff in the object?
}
});
}
});
Here is the file. The elements I would like to access are in the "_attachments" element of the object.
{
"_id": "efadd5913f5cfd254b2861efd4001cb7",
"_rev": "6-417588bbff9aa74726b11440a86a8532",
"_attachments": {
"Marie-Antoinette.json": {
"content_type": "application/json",
"revpos": 2,
"digest": "md5-Io/Pxakfp/4R8ntjQKWMDg==",
"length": 761,
"stub": true
}
}
}
I think what is throwing me off is that it is an object inside the _attachment section.
The Marie-Antoinette.json object is inside your _attachments object, but because it contains a . it can't be accessed using dot-notation. You'll have to use array-like notation, passing the key as a string like so:
success: function (response) {
console.log(response._attachments['Marie-Antoinette.json']);
}
If you have multiple "attachments", you can access them in a loop like this:
success: function (response) {
$.each(response._attachments, function (i, attachment) {
console.log(attachment);
});
}
You could use Object.keys to extract keys from _attachments object and then print it:
var title = Object.keys(r._attachments)[0];
console.log(title);
Or if you have multiple attachments:
var titles = Object.keys(r._attachments);
console.log(titles.join());
Object.keys always returns an array.
in your function:
success: function(r)
{
for (key in json._attachments) {
console.log(key); // gives the names
console.log(json._attachments[key]); // gives the content
}
}
that would give you the stuff in _attachments

Looking for parse assistance

This is the view from my browser:
{
"data": {
"request": [{
"query": "Lat 41.85 and Lon -87.65",
"type": "LatLon"
}],
"time_zone": [{
"localtime": "2012-02-14 16:05",
"utcOffset": "-6.0"
}]
}
}
Now, I am using this code to parse it:
function getTimeZone(latlong) {
jQuery(document).ready(function ($) {
$.ajax({
url: "http://www.worldweatheronline.com/feed/tz.ashx?key=[removed]&q=" + latlong + "&format=json",
dataType: "jsonp",
success: function (parsed_json) {
console.log(parsed_json.time_zone.utcOffset);
return parsed_json.time_zone.utcOffset;
},
error: function (parsed_json) {
//console.log("Error: " + parsed_json);
}
});
});
}
Every time I run the code, I am getting this error:
Uncaught TypeError: Cannot read property 'utcOffset' of undefined
Any assistance would be greatly appreciated.
View of the data being displayed to the console (only copied the part I'm interested in):
Result:
Object
data: Object
request: Array[1]
time_zone: Array[1]
0: Object
localtime: "2012-02-14 16:46"
utcOffset: "-6.0"
Actually, there are two issues:
1) to access the content, you need:
parsed_json.data.time_zone[0].utcOffset;
2) This is a bit more complex - you are using an asynchronous ajax callback - success() is not being called before your program finishes sending the ajax request and returns, and it does not return its results to the parent method.
The basically can't do it the way you want to, unless you use a synchronous fetch (a bad idea, since it'll lock up your browser until the response arrives).
Instead, take a callback parameter, which will be a function, as a parameter to your function, and call that with the result once it arrives:
i.e.
function getTimeZone(latlong, callback) {
jQuery(document).ready(function ($) {
$.ajax({
url: "http://www.worldweatheronline.com/feed/tz.ashx?key=[removed]&q=" + latlong + "&format=json",
dataType: "jsonp",
success: function (parsed_json) {
console.log(parsed_json.time_zone.utcOffset);
callback(latlong, parsed_json.data.time_zone[0].utcOffset);
},
error: function (parsed_json) {
//console.log("Error: " + parsed_json);
}
});
});
}
Then to use it:
getTimeZone(myLatLong, function(latLong, utcOffset) {
// ... do something with utcOffset here ...
});
Should be
return parsed_json.data.time_zone[0].utcOffset;
You have to look carefully at the returned JSON structure. It helps to break it up into separate lines and indent to reflect the nesting.
should it be parsed_json.data.time_zone[0].utcOffset?

Categories

Resources