Looping through nested arrays in Javascript - javascript

So I have an API that returns JSON data
Example JSON:
{
"result":"OK",
"data":[
{
"number":"613-555-5555",
"calls":30
},
{
"number":"613-666-5555",
"calls":100
}
]
}
I am trying to output this using javascript to show the following
[number, calls],[number, calls]
var response = response.data;
var length = response.length;
alert(data[0].number);
alert(data[0].calls);
for (var i = 0; i < data.length; i++) {
var arrayItem = data[i];
document.write(arrayItem);
}

This is simply a question of mapping your data to the desired format:
var final = response.data.map(function(item) {
return [item.number, item.calls];
});
console.log(final);
Here is a demo: http://jsfiddle.net/c8UQg/
EDIT:
I didn't realise you were looking for a string representation (I thought you wanted an array). If that is the case, please disregard the above.

If you like everything the way it is code wise, and just want to fix the error, then I suggest changing
var response = response.data;
to
var data = response.data;
Also, for the sake of debugging, change
document.write(arrayItem);
to
console.log(arrayItem);
http://jsfiddle.net/GptRW/

Related

How to loop in javascript?

i have a data response from API.
and how to loop this data, cause i only get first data. and this data not array.
data = [{"gamename":"game 1","gamelink":"link 1","image_link":"image 1","startfrom":"1"},{"gamename":"game 2","gamelink":"link 2","image_link":"imgae 2","startfrom":"2"}]
var json = response.data[0].games;
console.log(json);
if(Array.isArray(json)){
console.log('array');
}else{
console.log('not array');
}
for (var i = 0; i < json.length; i++) {
console.log('gamename : ' +json[i].gamename+ " - game link: " +json[i].image_link);
}
As #Robby Cornelissen has said, you are wrapping your array in another array, which is unnecessary and breaking your code. Your for loop only iterates over a single element in the outer array.
Also, it is strange for an API response to have a JSON string embedded as a string value within a JSON's property. You should post how you are retrieving the data.
response={data:[{games:`[{"gamename":"game 1","gamelink":"link 1","image_link":"image 1","startfrom":"1"},{"gamename":"game 2","gamelink":"link 2","image_link":"imgae 2","startfrom":"2"}]`}]}
var json = response.data[0].games;
console.log(json);
var array = JSON.parse(json);
console.log(array);
for (var i = 0; i < array.length; i++) {
console.log('gamename : ' +array[i].gamename+ " - game link: " +array[i].image_link);
}
you can use array.map(),array.forEach()
You may simply use foreach or for(on the base of length) or for of loop
Example
for (let element of data) {
console.log(element );
}
And to print data in format you wish, use like
for (let element of data) {
console.log('gamename : ' +element.gamename+ " - game link: " +element.image_link);
}
var data = [{"gamename":"game 1","gamelink":"link 1","image_link":"image 1","startfrom":"1"},{"gamename":"game 2","gamelink":"link 2","image_link":"imgae 2","startfrom":"2"}]
as you said if your array look like above one, use below code
data.forEach((el)=>console.log(el))
you will get every single object in that array.
if you are getting this data from a fetch you need to do res.json() in the fetch, an example is:
some data
[
{"gamename":"game 1","gamelink":"link 1","image_link":"image 1","startfrom":"1"},
{"gamename":"game 2","gamelink":"link 2","image_link":"imgae 2","startfrom":"2"}
]
fetch("someUrl")
.then(res => res.json()) // Here you parse the response
// Here you use forEach to loop in the response, and with destructuring you get the items with the name "gamename" and "gamelink"
.then(game => game.forEach(({gamename, gamelink}) => console.log(`gamename : ${gamename} - game link: ${gamelink}`)) // Here you log your data, and asumming that this is like the one above, you can do something like this
Try
for(var i =0; i<data.length; i++)
{
console.log(data[i]['gamename']);
console.log(data[i]['gamelink']);
}
I suspect your json is already parsed, and you don't need to re-parse it. A lot of http clients will do this if the content type header is application/json.
Try:
var games = response.data[0].games
for (var i = 0; i < games.length; i++) {
console.log('gamename : ' +games[i].gamename+ " - game link: " +games[i].image_link);
}

Get JSON stringify value

I have JSON stringify data like this :
[{"availability_id":"109465","date":"2017-02-21","price":"430000"},{"availability_id":"109466","date":"2017-02-22","price":"430000"},{"availability_id":"109467","date":"2017-02-23","price":"430000"}]
I want to get only price value of that data. I have tried this way but it doesn't work.
var stringify = JSON.stringify(values);
for(var i = 0; i < stringify.length; i++)
{
alert(stringify[i]['price']);
}
How could I to do that ?
This code will only fetch the price details.
var obj = '[{"availability_id":"109465","date":"2017-02-21","price":"430000"},{"availability_id":"109466","date":"2017-02-22","price":"430000"},{"availability_id":"109467","date":"2017-02-23","price":"430000"}]';
var stringify = JSON.parse(obj);
for (var i = 0; i < stringify.length; i++) {
console.log(stringify[i]['price']);
}
Observation :
If you want to parse the array of objects to get the property value you have to convert in into JSON object first.
DEMO
var jsonStringify = '[{"availability_id":"109465","date":"2017-02-21","price":"430000"},{"availability_id":"109466","date":"2017-02-22","price":"430000"},{"availability_id":"109467","date":"2017-02-23","price":"430000"}]';
var jsonObj = JSON.parse(jsonStringify);
for(var i = 0; i < jsonObj.length; i++)
{
alert(jsonObj[i]['price']);
}
you will geting a stringified object like this
var obj='[{"availability_id":"109465","date":"2017-02-21","price":"430000"},
{"availability_id":"109466","date":"2017-02-22","price":"430000"},
{"availability_id":"109467","date":"2017-02-23","price":"430000"}]';
parse your obj using JSON.parse(object)
then apply this loop ad let me know it get any error
lie this
var parseObject = JSON.parse(object);
instead of using stringify before selecting the data you should use your loop directly on the values array.
For example :
var priceArray = array();
values.forEach (data) {
alert(data['price'];
priceArray.push(data['price']);
}
stringify = JSON.stringify(values);
stringifiedPriceArray = JsON.stringify(priceArray);
Once stringified, you can't reach the data in your array

Merging JSON data from multiple URL's and sorting them based on a key

I need some help with Javascript. I have some data that I received from youtube APIs. The data is retrieved from the below URL's (I only showed 2 but I get from multiple other channels too)
https://www.googleapis.com/youtube/v3/search?key=AIzaSyDuS9LWv86VFCFr4ZD_Kwp5--Zi6YKo_rM&part=snippet,id&order=date&maxResults=50&channelId=UCpVm7bg6pXKo1Pr6k5kxG9A
https://www.googleapis.com/youtube/v3/search?key=AIzaSyDuS9LWv86VFCFr4ZD_Kwp5--Zi6YKo_rM&part=snippet,id&order=date&maxResults=50&channelId=UCLQZTXj_AnL7fDC8sLrTGMw
Every item in these json files has "publishedAt" value. Now I want to merge the data from both the JSON files and sort the list based on the "publishedAt" key i.e., the latest uploaded videos shown first.
Here is what I have currently which works perfectly for one file (I didn't do any magic, the URL itself sorts the items based on date)
$.getJSON(sourceUrl, function (data) {
//console.log(data);
//var you_data = JSON.stringify(data);
var videosCount = data.items.length;
console.log("The number of videos is: " + videosCount);
for ( i = 0 ; i < videosCount; i++) {
var title = data.items[i].snippet.title;
var url = "https://www.youtube.com/watch?v=" + data.items[0].id.videoId;
$("#reply").append(" " + title + "<br><br><br>");
//console.log(title);
//console.log(url);
};
});
How do I get this done?
EDITED (my thoughts):
Something that I can think of is using nested objects. I can create a new object that two looks something like:
grand_parent_object = { {'publishedAt':xxxxxxxx, 'wholeItem':{the whole item as shown in the JSON file}}, {'publishedAt':xxxxxxxx, 'wholeItem':{the whole item2 as shown in the JSON file}}, etc}
here the parent_object is {'publishedAt':xxxxxxxx, 'wholeItem':{the whole item as shown in the JSON file}}
Maybe I should sort the parent_objects based on their 'publishedAt' values first and then that should do the job???? PS: 'publishedAt' in parent_object is the same as 'publishedAt' in the 'wholeItem' value.
Solution:
I used Ross's logic and it worked. I had issues with .getJson since it wouldn't update the global variable, wholearray. So I used .ajax and it worked. Here is my working code:
function getAjaxData(sourceUrl) {
$.ajax({
async:false,
url:sourceUrl,
success: function(data) {
var videosCount = data.items.length;
for ( var i = 0 ; i < videosCount; i++) {
var tempobject = {};
tempobject.published = data.items[i].snippet.publishedAt;
tempobject.wholeItem = data.items[i];
wholearray.push(tempobject);
}
}
});
}
One solution is to create a new array of object literals, then sort the array based on the key:
var array = [];
$.getJSON(url, function(data){
for (var i=0; i<data.length; i++){
var object = {}
object.published = data.items[i].snippet.publishedAt
object.wholeItem = data.items[i]
array.push(object);
}
})
$.getJSON(otherUrl, function(data){
for (var i=0; i<data.length; i++){
var object = {}
object.published = data.items[i].snippet.publishedAt
object.wholeItem = data.items[i]
array.push(object);
}
})
Have a listener that waits for both AJAX calls to finish, then you can sort:
array.sort(function(a,b) { return a.published - b.published; });
This question gives more info on sorting
This may not be the most efficient way, but it's the first that comes to mind and will work swell!

return data of a field in store in array

This might be a question of pure javascript but somehow I cant get this right. I am working on extjs4.2 using sencha architect. I have a json response sent from server as
{
"data": [{
"ExamID": 1,
"ExamName": "Semester-1",
"MaxMarks": 100
}, {
"ExamID": 4,
"ExamName": "Test-1",
"MaxMarks": 10
}, {
"ExamID": 5,
"ExamName": "Test-2",
"MaxMarks": 10
}]
}
what I am looking for is to reconfigure grid using the data of "ExamName" only. So "ExamName" shall be passed as array in reconfigure() function.
I am unable to get "ExamName" in array form. Your help is highly appreciated
var gridStore = Ext.data.StoreManager.get('ClassSemesterStore');
var g = gridStore.load( {params : {ClassID: ClassData }});
var data = g.data;
var length = data.getCount();
var examName = [];
for(var i = 0; i < length; i++){
examName.push(data[i]['ExamName']);
}
it says "Uncaught TypeError: Cannot read property 'ExamName' of undefined"
I think if I understand you correctly, you're trying to have examName be a new array with it's contents being each ExamName in your response data? If so, this should work.
var data = {"data":[{"ExamID":1,"ExamName":"Semester-1","MaxMarks":100},{"ExamID":4,"ExamName":"Test-1","MaxMarks":10},{"ExamID":5,"ExamName":"Test-2","MaxMarks":10}]}
var examName = [];
for(var i = 0; i < data.data.length; i++){
examName.push(data.data[i]['ExamName']);
}
now examName is an Array with "Semester-1", "Test-1", and "Test-2"
Store's data in not an array. It's a Mixed Collection I think. So either use the following:
var examName = [];
for(var i = 0; i < length; i++){
examName.push(data.items[i].data['ExamName']);
}
or better yet get the information from your source like the people suggested.
Another good alternative is Store's collect.
You can do sth like:
gridStore.collect('ExamName')
The error was because of asynchronous nature of store loading:
var g = Store.load({
params : {ClassID: ClassData },
callback : function(records, operation, success){
var Excerpt = []; // start with empty array
Ext.each(records, function(item) {
// add the fields that you want to include
var Obj = {
third_field: item.get('ExamName')
};
Excerpt.push(Obj); // push this to the array
}, this);
console.log(Excerpt);
}
});

jQuery: Convert string with comma separated values to specific JSON format

I've been losing hours over something that might be trivial:
I've got a list of comma-separated e-mail addresses that I want to convert to a specific JSON format, for use with the Mandrill API (https://mandrillapp.com/api/docs/messages.JSON.html)
My string:
var to = 'bigbadwolf#grannysplace.com,hungry#hippos.com,youtalkin#to.me';
What (I think) it needs to be:
[
{"email": "bigbadwolf#grannysplace.com"},
{"email": "hungry#hippos.com"},
{"email": "youtalkin#to.me"}
]
I've got a JSFiddle in which I almost have it I think:
http://jsfiddle.net/5j8Z7/1/
I've been looking into several jQuery plugins, amongst which: http://code.google.com/p/jquery-json
But I keep getting syntax errors.
Another post on SO suggested doing it by hand: JavaScript associative array to JSON
This might be a trivial question, but the Codecadamy documentation of the Mandrill API has been down for some time and there are no decent examples available.
var json = [];
var to = 'bigbadwolf#grannysplace.com,hungry#hippos.com,youtalkin#to.me';
var toSplit = to.split(",");
for (var i = 0; i < toSplit.length; i++) {
json.push({"email":toSplit[i]});
}
Try this ES6 Version which has better perform code snippet.
'use strict';
let to = 'bigbadwolf#grannysplace.com,hungry#hippos.com,youtalkin#to.me';
let emailList = to.split(',').map(values => {
return {
email: values.trim(),
}
});
console.log(emailList);
Try changing the loop to this:
var JSON = [];
$(pieces).each(function(index) {
JSON.push({'email': pieces[index]});
});
How about:
var to = 'bigbadwolf#grannysplace.com,hungry#hippos.com,youtalkin#to.me',
obj = [],
parts = to.split(",");
for (var i = 0; i < parts.length; i++) {
obj.push({email:parts[i]});
}
//Logging
for (var i = 0; i < obj.length; i++) {
console.log(obj[i]);
}
Output:
Object {email: "bigbadwolf#grannysplace.com"}
Object {email: "hungry#hippos.com"}
Object {email: "youtalkin#to.me"}
Demo: http://jsfiddle.net/tymeJV/yKPDc/1/

Categories

Resources