jQuery each loop for json data by index - javascript

I have some json data that the id number will change, so instead of referencing it by ID number I would like to reference it by array index.
I am looking to alert the source which would be the image URL https://upload.wikimedia.org/wikipedia/commons/thumb/8/89/Chuck_Schumer_official_photo.jpg/240px-Chuck_Schumer_official_photo.jpg
This is a sample of the json data:
{
"batchcomplete":"",
"query":{
"normalized":[
{
"from":"Chuck_Schumer",
"to":"Chuck Schumer"
}
],
"pages":{
"326708":{
"pageid":326708,
"ns":0,
"title":"Chuck Schumer",
"thumbnail":{
"source":"https://upload.wikimedia.org/wikipedia/commons/thumb/8/89/Chuck_Schumer_official_photo.jpg/240px-Chuck_Schumer_official_photo.jpg",
"width":240,
"height":300
},
"pageimage":"Chuck_Schumer_official_photo.jpg"
}
}
}
}
This is my JavaScript attempt:
function processWikiData(wikiData){
$(wikiData.query).each(function(index, query_item) {
$(query_item.pages).each(function(index, page_item) {
// I was hoping to get the array's first index here but clearly this is wrong
$(page_item.[0]).each(function(index, wiki_id) {
$(wiki_id.thumbnail).each(function(index, thumbnail_item) {
alert(thumbnail_item.source);
});
});
});
});
}

Related

Push "programmatic" array to an Object's array property

I'm building a Thesaurus app, and for this question, the key note is that i'm adding a list of synonyms(words that have the same meaning) for a particular word(eg - "feline", "tomcat", "puss" are synonyms of "cat")
I have a Word object, with a property - "synonyms" - which is an array.
I'm going to add an array of synonyms to the Word synonyms property.
According to the MongoDb documentation see here, the only way to append all the indexes of an array to a document's array property at once is to try the following:
db.students.update(
{ _id: 5 },
{
$push: {
quizzes: {
$each: [ { wk: 5, score: 8 }, { wk: 6, score: 7 }, { wk: 7, score: 6 } ],
}
}
}
)
Let's re-write that solution to suit my data, before we venture further.
db.words.update(
{ baseWord: 'cat' },
{
$push: {
synonyms: {
$each: [ { _id: 'someValue', synonym: 'feline' }, { _id: 'someValue', synonym: 'puss' }, { _id: 'someValue', synonym: 'tomcat' } ],
}
}
}
)
Nice and concise, but not what i'm trying to do.
What if you don't know your data beforehand and have a dynamic array which you'd like to feed in?
My current solution is to split up the array and run a forEach() loop, resulting in an array being appended to the Word object's synonyms array property like so:
//req.body.synonym = 'feline,tomcat,puss';
var individualSynonyms = req.body.synonym.split(',');
individualSynonyms.forEach(function(synonym) {
db.words.update(
{ "_id": 5 },
{ $push: //this is the Word.synonyms
{ synonyms:
{
$each:[{ //pushing each synonym as a Synonym object
uuid : uuid.v4(),
synonym:synonym,
}]
}
}
},{ upsert : true },
function(err, result) {
if (err){
res.json({ success:false, message:'Error adding base word and synonym, try again or come back later.' });
console.log("Error updating word and synonym document");
}
//using an 'else' clause here will flag a "multiple header" error due to multiple json messages being returned
//because of the forEach loop
/*
else{
res.json({ success:true, message:'Word and synonyms added!' });
console.log("Update of Word document successful, check document list");
}
*/
});
//if each insert happen, we reach here
if (!err){
res.json({ success:true, message:'Word and synonyms added!.' });
console.log("Update of Word document successful, check document list");
}
});
}
This works as intended, but you may notice and issue at the bottom, where there's a commented out ELSE clause, and a check for 'if(!err)'.
If the ELSE clause is executed, we get a "multiple headers" error because the loop causes multiple JSON results for a single request.
As well as that, 'if(!err)' will throw an error, because it doesn't have scope to the 'err' parameter in the callback from the .update() function.
- If there was a way to avoid using a forEach loop, and directly feed the array of synonyms into a single update() call, then I can make use of if(!err) inside the callback.
You might be thinking: "Just remove the 'if(!err)' clause", but it seems unclean to just send a JSON response without some sort of final error check beforehand, whether an if, else, else if etc..
I could not find this particular approach in the documentation or on this site, and to me it seems like best practice if it can be done, as it allows you to perform a final error check before sending the response.
I'm curious about whether this can actually be done.
I'm not using the console, but I included a namespace prefix before calling each object for easier reading.
There is not need to "iterate" since $each takes an "array" as the argument. Simply .map() the produced array from .split() with the additional data:
db.words.update(
{ "_id": 5 },
{ $push: {
synonyms: {
$each: req.body.synonym.split(',').map(synonym =>
({ uuid: uuid.v4, synonym })
)
}
}},
{ upsert : true },
function(err,result) {
if (!err){
res.json({ success:true, message:'Word and synonyms added!.' });
console.log("Update of Word document successful, check document list");
}
}
);
So .split() produces an "array" from the string, which you "transform" using .map() into an array of the uuid value and the "synonym" from the elements of .split(). This is then a direct "array" to be applied with $each to the $push operation.
One request.

how to change .immediate.types.apps to dynamic text

this code is working, but i need the $push query field to be dynamin like this
generalrecommendations[req.body.term].types.apps please help.
here is my mongodb database:
"generalrecommendations" : {
"immediate" : {
"types" : {
"apps" : [
"1"
]
}
}
}
and here is my code:
db.collection('colleges').update(
{ '_id': new ObjectId(req.body.college) },
{
$push:{ "generalrecommendations.immediate.types.apps": temp2[key1][i] }
}, function (err, result) {
})
finds the id and appends new item to exixting array. here immediate is hardcoded but now i need to change it to dynamic like this req.body.term
to make the query field dynamic you need to use [] operators while entering your query Field. Lets say your
req.body.term = immediate;
then instead of
$push:{ "generalrecommendations.immediate.types.apps": temp2[key1][i] }
use
$push:{ ["generalrecommendations"+ req.body.term +"types.apps"]: temp2[key1][i] }
adding [] to your query field will make it dynamic.

Cannot Read JSON Array Within JSON Array Using jQuery $.getJSON

I cannot get the items of an JSON array within an JSON object. Here's what my JSON looks like:
[
{
"category":9,
"channels":[
{
"id":5,
"title":"MYTITLE",
"active":true,
"recent":true,
"image":"/arts/736c1ad4-2dbe-40a6-859d-8dba89c26ec2.jpg",
"recent_tracks":{
"vip":"https://api.xyzsite.com/recent_tracks/vip-3.json",
"free":"https://api.xyzsite.com/recent_tracks/free-3.json"
},
"additional_vip_channels":[
{
"channel_name":"vip-3a",
"recent_tracks_uri":"https://api.xyzsite.com/recent_tracks/vip-3a.json",
"streams":{
"320":"http://streams.xyzsite.com/api/914/320/stream",
"64":"http://streams.xyzsite.com/api/914/64/stream",
"192":"http://streams.xyzsite.com/api/914/192/stream"
}
}
],
"streams":{
"free":"http://streams.xyzsite.com/api/31/56/stream",
"free_56":"http://streams.xyzsite.com/api/31/56/stream",
"free_128":"http://streams.xyzsite.com/api/31/128/stream",
"320":"http://streams.xyzsite.com/api/33/320/stream",
"64":"http://streams.xyzsite.com/api/33/64/stream",
"192":"http://streams.xyzsite.com/api/33/192/stream"
}
},
I use the following code to get the values:
$.getJSON('https://api.xyzsite.com/channels.json', function(response) {
$.each(response, function (index, value) {
var catId = value.category;
$.each(value.channels, function (index, value) {
XYZApp.channels.push({
categoryId: catId,
id: value.id,
name: value.title,
image: value.image,
recent_tracks: {
vip: value.recent_tracks.vip,
free: value.recent_tracks.free
},
streams: {
free_128: value.streams.free_128,
member_320: value.streams["320"],
member_64: value.streams["64"],
member_192: value.streams["192"]
}
});
console.log(value.additional_vip_channels);
});
});
}).
then ...
I can get the values, but I cannot read the additional_vip_channels array within the .each jQuery function. I already tried:
value.additional_vip_channels.channel_name
value.additional_vip_channels[0].channel_name
value.additional_vip_channels["0"].channel_name
but none of them work.
And the log output is also here:
How can I get the channel_name and other data in additional_vip_channels?
I believe that you would want:
channels[0]['additional_vip_channels'][0]['channel_name']
Equally, this should work: (just a different way of selecting)
channels[0].additional_vip_channels[0].channel_name
Hope that helps and works :)

how to access the information1 data

Am trying to access the data from the following JSON . Am Getting response after hitting the server and i need to access the data present in the information1 field.
{
"Test1":[
{
"id1":0,
"Test2":[
{
"Information1":"info1",
"name":"Testing",
"defnitions":[
{
"displayname":"displayame"
},
{
"displayname2":"displayame2"
}
],
"information2":"info2"
}
],
"information3":"info3",
"information4":"info4"
}
]
}
Cause you are using square brackets, it means you have an array. Consequently, to access to your neccessary object you should use:
var data={
"Test1":[
{
"id1":0,
"Test2":[
{
"Information1":"info1",
"name":"Testing",
"defnitions":[
{
"displayname":"displayame"
},
{
"displayname2":"displayame2"
}
],
"information2":"info2"
}
],
"information3":"info3",
"information4":"info4"
}
]
};
var yourObject=data.Test1[0].Test2[0];
To parse JSON response just use stringify method:
var theWholeObject=JSON.stringify(data);

json response handling from soap wsdl

below is the response from soapWSDL in json.i need to print the pname,pjob .i can able to print "client":"http://xmlns.oracle.com/InternetMobile/AbsManagement/BPELProcessSubList", using alert(result.responseJSON.Envelope.Body.processResponse.client); but cant able to print sublist.pname which displays undefined error
{
"Envelope":{
"Body":{
"processResponse":{
"client":"http:\/\/xmlns.oracle.com\/InternetMobile\/AbsManagement\/BPELProcessSubList",
"subList":[
{
"personid":"30979",
"pjob":"Senior Consultant",
"pname":"Imad El Kustomany"
},
{
"personid":"30980",
"pjob":"Senior Consultant",
"pname":"Abdul Rahman Zaky"
}
],
"xmlns":"http:\/\/xmlns.oracle.com\/InternetMobile\/AbsManagement\/BPELProcessSubList"
}
},
}
Try result.responseJSON.Envelope.Body.processResponse.subList[0].pname and result.responseJSON.Envelope.Body.processResponse.subList[1].pname. subList is an array so you can loop and use index as well
Sublist is an array so you need:
alert(result.responseJSON.Envelope.Body.processResponse.client.subList[0].pname);
or if you want to display pnames of all items
result.responseJSON.Envelope.Body.processResponse.client.subList.forEach(function(el){
alert(el.pname);
});

Categories