How to get information from too array json in AngularJS - javascript

I have a JSON file that has 2 arrays containing some data that I'd like to access on my AngularJS website. Now what I want is to get only one object from the 2 arrays.
JSON data
[
{
"DailyForecasts": [
{
"key": "32.48,44.46",
"class": "forecast",
"validDate": 1484236800,
"maxTemp": 17,
"minTemp": 3,
"precip_type": "rain",
"day": {
"humid": 34,
"wSpeed": 20,
"wDir": 297,
"pop": 0,
"uv": 2,
"icon": 34,
"wDirText": "غرب-شمال غ",
"phrase": "مشمس بصورة كلية",
"bluntPhrase": "",
"precip_type": "rain",
"snwAccumPhrase": "",
"snwAccumPhraseTerse": "",
"extQual": "",
"weatherCode": "3400"
},
"night": {
"humid": 64,
"wSpeed": 20,
"wDir": 297,
"pop": 0,
"uv": 0,
"icon": 33,
"wDirText": "غرب-شمال غ",
"phrase": "صافي بصورة كلية",
"bluntPhrase": "",
"precip_type": "precip",
"snwAccumPhrase": "",
"snwAccumPhraseTerse": "",
"extQual": "",
"weatherCode": "3300"
}
},
{
"key": "32.48,44.46",
"class": "forecast",
"validDate": 1484323200,
"maxTemp": 17,
"minTemp": 5,
"precip_type": "rain",
"day": {
"humid": 48,
"wSpeed": 14,
"wDir": 287,
"pop": 0,
"uv": 3,
"icon": 32,
"wDirText": "غرب-شمال غ",
"phrase": "مشمس",
"bluntPhrase": "",
"precip_type": "rain",
"snwAccumPhrase": "",
"snwAccumPhraseTerse": "",
"extQual": "",
"weatherCode": "3200"
},
"night": {
"humid": 67,
"wSpeed": 14,
"wDir": 287,
"pop": 10,
"uv": 0,
"icon": 31,
"wDirText": "غرب-شمال غ",
"phrase": "صافي",
"bluntPhrase": "",
"precip_type": "rain",
"snwAccumPhrase": "",
"snwAccumPhraseTerse": "",
"extQual": "",
"weatherCode": "3100"
}
}
]
}
]
Controller Code
app.controller('Hillahctlr', function($scope, $http, wind, arrivecss, windname, icons) {
$scope.wind_dir = wind;
$scope.icons = icons;
$scope.arrivecss = arrivecss;
$scope.windname = windname;
var service_url = "/key=e88d1560-a740-102c-bafd-001321203584&units=m&locale=ar&cb=JSON_CALLBACK";
$http.jsonp(service_url)
.success(
function(data) {
console.log(data);
yData = data.HourlyForecasts;
$scope.ali = [];
for (var i = 0; i < 9; i++)
{
$scope.ali[i] = {
dayes: yData[i].temp,
};
}
})
})
}
and loop inside this array using ng-repeat , but its not working for me , this is code:
HTML
<div class="ForecastArea-Day Last weatherteble" ng-repeat="alis in dayes">
{{alis.dayes}}
</div>
I get this error: Error: yData is not defined Any help please ?

Use yData = data[0].HourlyForecasts;. The JSON starts with [ { "DailyForecasts": [ which means it is an array of objects.
work fine thanks , what about the object day inside HourlyForecasts
when run get yData[i].day is undefined
see my short code
yday = data[0].DailyForecasts;
$scope.daily = [];
for(var i=0; i<9; i++) {
$scope.daily[i] = {maxTemp: yData[i].maxTemp,
minTemp: yData[i].minTemp,
validDate: yData[i].validDate,
icon: yData[i]day.icon, };
}
All I see is a missing dot ".":
// icon: yData[i]day.icon, };
icon: yData[i].day.icon, };
// ^ --- put a dot here
Also be sure to declare yday as a var:
//yday = data[0].DailyForecasts;
var yday = data[0].DailyForecasts;
Without a var declaration, it will polute global namespace.

Try this.
var alis = [];
alis = {dayes: yData[i].temp,};
$scope.ali = ali;
<div class="ForecastArea-Day Last weatherteble" ng-repeat="alis in ali.dayes">
{{alis.day}}
</div>

Related

Get Father and Children in an API with APPS SCRIPT (GSHEETS)

i'm using google apps script, and I have a JSON array consisting of nested parent and child objects.
"logisticalHierarchies": [
{
"product_key_id": 48232671,
"gtin": "05449000696878",
"lastRequest": null,
"productIdentifier": null,
"children": [
{
"product_key_id": 48232673,
"gtin": "05449000283863",
"quantity": 130,
"productIdentifier": null,
"children": [
{
"product_key_id": 48232457,
"gtin": "05449000283856",
"quantity": 4,
"productIdentifier": null,
"children": [
{
"product_key_id": 48232675,
"gtin": "05449000214843",
"quantity": 6,
"productIdentifier": null,
"children": [],
"contentOwner_id": 10525,
"isMainHierarchyUnit": false,
I would like by entering the GTIN object as parameters, to succeed in recovering the GTIN object of the father of the product that I have just entered.
For example if I enter the GTIN: 05449000283856
I get the GTIN FATHER: 05449000283863
For the moment I am able to retrieve only the first GTIN of the list (the first father) using this script:
var url='https://apis.alkemics.com/public/v1/products?'+params;
//Logger.log(url);
var content =UrlFetchApp.fetch(url, options);
//Logger.log(content);
//Logger.log(content.getResponseCode())
if (content. getResponseCode() ==200) {
var return =JSON.parse(content.getContentText());
next_page=back.next_page;
var data=return.data;
for(i=0; i<data.length;i++) {
var product=data[i]; // A product in JSON format
var childrens = data.map(({logisticalHierarchies}) => logisticalHierarchies.map(o => [o.children?.gtin || ""]));
Logger.log(childrens)
var line=[
product.gtin,
product.logisticalHierarchies[0] != null? product.logisticalHierarchies[0].children[0].gtin: ' ',
];
So a recursion would help, passing the father as you go into deeper level. This one written for readability not for efficiency as you should break from the loop early if you find the searched item.
var logisticalHierarchies = [{
"product_key_id": 48232671,
"gtin": "05449000696878",
"lastRequest": null,
"productIdentifier": null,
"children": [{
"product_key_id": 48232673,
"gtin": "05449000283863",
"quantity": 130,
"productIdentifier": null,
"children": [{
"product_key_id": 48232457,
"gtin": "05449000283856",
"quantity": 4,
"productIdentifier": null,
"children": [{
"product_key_id": 48232675,
"gtin": "05449000214843",
"quantity": 6,
"productIdentifier": null,
"children": [],
"contentOwner_id": 10525,
"isMainHierarchyUnit": false,
}, {
"product_key_id": 12323,
"gtin": "05449000214847",
"quantity": 6,
"productIdentifier": null,
"children": [],
"contentOwner_id": 10525,
"isMainHierarchyUnit": false,
}]
}]
}]
}]
function find_gtin_father(arr, gtin, parent) {
parent = parent || null;
var found = null;
arr.forEach(function(item) {
if (item.gtin === gtin) {
found = parent;
} else {
if (item.children) {
found = found || find_gtin_father(item.children, gtin, item);
}
}
})
return found;
}
var item = find_gtin_father(logisticalHierarchies, "05449000214847")
console.log(item)
.as-console-wrapper {max-height: 100% !important}

I need to parse json array which consist of array inside object

Here is my JSON array which I need to parse using javascript code.
{
"individualTicketList": [{
"TicketID": 58,
"ResponderID": 1,
"Subject": "test sub",
"DueByDate": "2021-10-12"
},
{
"TicketID": 59,
"ResponderID": 1,
"Subject": "test",
"DueByDate": "2021-10-12"
}]
}
I am having an above json array and i need to display subject of each object from my json `which is inside individualticketlist here is my code.`
for(var i=0;i<jsonString.length;i++)
{
alert(a.individualTicketList[i].DueByDate);
}
Here's how to loop through it
let json = {
"individualTicketList": [{
"TicketID": 58,
"ResponderID": 1,
"Subject": "test sub",
"DueByDate": "2021-10-12"
}, {
"TicketID": 59,
"ResponderID": 1,
"Subject": "test",
"DueByDate": "2021-10-12"
}]
}
let arr = json["individualTicketList"]
for (var i = 0; i < arr.length; i++) {
console.log(arr[i].Subject);
console.log(arr[i].DueByDate);
//your other code here
}

how to insert an array in ajax?

I have modal, inside the modal there is a form when i click the submit button it will do this.
jquery code:
$('#add-new-content-form').on('submit', e => {
e.preventDefault();
//I want to add this block dates to the data
let blockdates = $("#block-dates").val();
let title = $("#card-title").val();
let catalogId = $("#catalog").val();
let categoryId = $("#category").val();
let subcategoryId = $('#subcategory').val();
let why = $("#why").val();
let description = $('#card-description').val();
let cancellationPolicy = $('#cancellation-policy').val();
let displayPrice = $('#display-price').val();
let displayDiscounted = $('#discounted-price').val();
let displayMaxPax = $('#display-maxpax').val();
let data = {
"blockDates":[
{
"description": "national araw ng mga puso day!",
"notAvailableDate": "2019-02-14 10:00:00"
},
{
"description": "chinese new year!",
"notAvailableDate": "2019-02-25 10:00:00"
}
],
"title": title,
"catalogId": catalogId,
"categoryId": categoryId,
"subcategoryId": subcategoryId,
"why": why,
"description": description,
"cancellationPolicy": cancellationPolicy,
"displayPrice": displayPrice,
"displayDiscounted": displayDiscounted,
"displayMaxPax": displayMaxPax
};
let content = ajax("api/unitContents", JSON.stringify(data), "POST");
// window.location.replace("/category");
});
Now, in the postman there is something just like this:
{
"blockDates":[
{
"description": "national araw ng mga puso day!",
"notAvailableDate": "2019-02-14 10:00:00"
},
{
"description": "chinese new year!",
"notAvailableDate": "2019-02-25 10:00:00"
}
],
"location":{
"identifier":"UBZ190asas11",
"name": "abulalas,purok 4",
"address" : "abulalas1 hagonoy bulacan",
"lat" : 12141.00,
"lng" : 123251.00
},
"units": 2,
"title": "sample unit content",
"catalogId": 6,
"categoryId": 22,
"subcategoryId": 13,
"contentOptions": [
{
"name":"bannana boat",
"maxPax":8,
"isAvailableDayTime":[
9,10,11,12,13,15,16,17,18,
33,34,35,36,37,39,38,39,40,
56,57,58,59,60,62,63,64,65,
80,81,82,83,84,86,87,88,89,
104,105,106,107,108,110,111,112,113,
128,129,130,131,132,134,135,136,137,
152,153,154,155,156,158,159,160,161
],
"inventoryNeededSet":[
{
"inventoryId": 1,
"count":1
},
{
"inventoryId": 1,
"count":2
}
],
"paxPrices": [
{
"count": 5,
"pricePerPax": 200,
"totalPrice": 1000,
"fee": 100
},
{
"count": 1,
"pricePerPax": 200,
"totalPrice": 200,
"fee": 10
}
]
},
{
"name":"bannana with island tour",
"maxPax":10,
"isAvailableDayTime":[
9,10,11,12,13,15,16,17,18,
33,34,35,36,37,39,38,39,40,
56,57,58,59,60,62,63,64,65,
80,81,82,83,84,86,87,88,89,
104,105,106,107,108,110,111,112,113,
128,129,130,131,132,134,135,136,137,
152,153,154,155,156,158,159,160,161
],
"inventoryNeededSet":[
{
"inventoryId": 1,
"count":2
},
{
"inventoryId": 1,
"count":2
}
],
"paxPrices": [
{
"count": 5,
"pricePerPax": 200,
"totalPrice": 1000,
"fee": 100
},
{
"count": 1,
"pricePerPax": 200,
"totalPrice": 200,
"fee": 10
}
]
}
],
"photos": [
"https://samplephoto1.com",
"https://samplephoto2.com",
"https://samplephoto3.com"
],
"videos": [
"https://samplevid1.com",
"https://samplevid2.com",
"https://samplevid3.com"
],
"why": "sample why",
"description": "sample desc",
"cancellationPolicy":"cancellationPolicy",
"displayPrice": 300,
"displayDiscounted": 250,
"displayMaxPax": 2
}
the thing is, I want to save the blockdate, what is the syntax of inserting the blockdates?
=======================UPDATED======================
Try this before stringifying the data variable:
data.blockdates = $("#block-dates").val();
To execute your code jQuery is needed. Try after inserting <script src='https://code.jquery.com/jquery-3.3.1.min.js'></script> before your code.
If you have let blockdates = $("#block-dates").val();
You can append blockdates into data like this
data['blockdates']=blockdates;
You may need to keep the elements in an object first. You can then add them to the array.
blockDates= [];
var description = $("#card-description").val();
var notAvailableDate = $("##block-dates").val();
var blockdate = {description, notAvailableDate};
blockDates.push(blockdate);
in this way => let content = ajax("api/unitContents", JSON.stringify(data, blockDates), "POST");
or
let data = {
"title": title,
"catalogId": catalogId,
"categoryId": categoryId,
"subcategoryId": subcategoryId,
"why": why,
"cancellationPolicy": cancellationPolicy,
"displayPrice": displayPrice,
"displayDiscounted": displayDiscounted,
"displayMaxPax": displayMaxPax,
"blockDates": blockDates
};
in this way => `let content = ajax("api/unitContents", JSON.stringify(data), "POST");`

Using jQuery to get JSON Data

I have a JSON response that shows like this:
{
"gameId": 2540832082,
"mapId": 12,
"gameMode": "ARAM",
"gameType": "MATCHED_GAME",
"gameQueueConfigId": 65,
"participants": [
{
"teamId": 100,
"spell1Id": 32,
"spell2Id": 7,
"championId": 25,
"profileIconId": 774,
"summonerName": "MLG Elan",
"bot": false,
"summonerId": 77477471,
"runes": [],
"masteries": [
{
"rank": 5,
"masteryId": 6111
},
{
"rank": 1,
"masteryId": 6122
},
{
"rank": 2,
"masteryId": 6131
}
]
},
{
"teamId": 100,
"spell1Id": 4,
"spell2Id": 32,
"championId": 120,
"profileIconId": 774,
"summonerName": "Nuetzlich",
"bot": false,
"summonerId": 43800105,
"runes": [
{
"count": 6,
"runeId": 5245
},
{
"count": 2,
"runeId": 5335
}
],
"masteries": [
{
"rank": 3,
"masteryId": 6114
},
{
"rank": 5,
"masteryId": 6312
},
{
"rank": 1,
"masteryId": 6322
},
{
"rank": 5,
"masteryId": 6331
},
{
"rank": 1,
"masteryId": 6343
},
{
"rank": 5,
"masteryId": 6351
},
{
"rank": 1,
"masteryId": 6362
}
]
},
{
"teamId": 100,
"spell1Id": 13,
"spell2Id": 7,
"championId": 67,
"profileIconId": 19,
"summonerName": "Sonicmońgrel",
"bot": false,
"summonerId": 82267777,
"runes": [
{
"count": 6,
"runeId": 5245
},
{
"count": 2,
"runeId": 5335
}
],
"masteries": [
{
"rank": 5,
"masteryId": 6312
},
{
"rank": 1,
"masteryId": 6323
},
{
"rank": 5,
"masteryId": 6331
},
{
"rank": 1,
"masteryId": 6343
},
{
"rank": 4,
"masteryId": 6351
}
]
},
I'm struggling to get the "summonerNames" for each player and display them on the site :(
What jQuery do I need?
This is what gets the data:
function getCurrentGame(summonerID) {
$.ajax({
url: "https://euw.api.pvp.net/observer-mode/rest/consumer/getSpectatorGameInfo/EUW1/" + summonerID + "?api_key=" + APIKEY,
type: 'GET',
dataType: 'json',
data: {
},
What do I need in here:
success: function (resp) {
}
To display the summoner names?
I have this in my HTML to simply build the list from the names:
Current Players (<span id="listPlayers"></span>)
<hr />
<span id="playerNames"></span>
Feel free to amend it in whatever way, I just really can't figure out how to list the player names :(
THANKS!!!
Your whole JSON object is the resp.
Let's say you want to access "gameMode": "ARAM", it will be resp.gameMode.
Let's you want want to access "summonerName": "MLG Elan", it will be resp.participants.summonerName ( because summonerName is inside an array called participants )
Try this
var obj = jQuery.parseJSON( resp );
alert( obj.participants[0].summonerName);
In your json data.participants is an array, you can use Array#map to get all names:
var names = data.participants.map(function(item) {
return item.summonerName;
});
You don't need jquery for that
JSON
var json = yourJSON;
JavaScript
var lenght = json.participants.length;
var summonerName = "";
for (i = 0; i < lenght ; i++){
summonerName += json.participants[i].summonerName.toString() + ", ";
}
document.getElementById("playerNames").innerText = summonerName;
HTML
<span id="playerNames"></span>
The resp parameter is a JavaScript object created by the returned Json. summonerName is an attribute of each participant and participants is an array of objects. So you need to iterate through the participants array and get the name for each participant. Try something like this
success: function (resp) {
var participants = resp.participants,
names = "",
spanElement = document.getElementById("playerNames");
participants.forEach(function(part){
names = names + part.summonerName + " ";
}
spanElement.innerText = names ;
}

undefined JSON values in Javascript error

I am reading through a JSON object, trying to loop through the text and create substrings of the text. It is, for some reason coming back as "cannot read property 'roles' of undefined." What am I missing?
// target language text
var text1 = obj[0].tgtLanguageSentences[0].text;
var strArry1 = [];
var colorArr1 = ["DarkSalmon", "ForestGreen", "Brown"];
for(var t=0; t<obj[0].tgtLanguageSentences[0].roles.length; t++)
{
// create variables representing substrings of the Source language Sentence
var tgt1 = text1.substring((obj[t].tgtLanguageSentences[t].roles[t].beginOffset - obj[t].tgtLanguageSentences[t].roles[t].beginOffset),(obj[t].tgtLanguageSentences[t].roles[t].beginOffset - 1));
var tgt2 = text1.substring(obj[t].tgtLanguageSentences[t].roles[t].beginOffset,obj[t].tgtLanguageSentences[t].roles[t].endOffset);
var tgt3 =
text1.substring(obj[t].tgtLanguageSentences[t].roles[t].endOffset,obj[t].tgtLanguageSentences[t].text.length);
strArry.push('<h4>'+tgt1+'</h4>');
strArry.push('<h4>'+'<font color="'+colorArr1[i]+'">"'+tgt2+'</font>'+'</h4>');
if(i == obj[0].tgtLanguageSentences[0].roles[0].length-1)
{
strArry.push('<h4>'+tgt3+'</h4>');
}
text1 = s3;
}
Please see the JSON object in reference below:
[
{
"description": "",
"roles": [
{
"name": "thing commented on"
},
{
"name": "commentor"
}
],
"srcLanguageSentence": {
"roles": [
{
"beginOffset": 23,
"endOffset": 30,
"name": "thing commented on",
"text": "on them"
},
{
"beginOffset": 5,
"endOffset": 7,
"name": "commentor",
"text": "We"
}
],
"text": " `` We wo n't comment on them . '' ",
"verb": {
"beginOffset": 15,
"endOffset": 22,
"text": "comment"
}
},
"tgtLanguageSentences": [
{
"roles": [
{
"beginOffset": 1,
"endOffset": 31,
"name": "thing commented on",
"text": "Weitere Aspekte der Kommission"
},
{
"beginOffset": 44,
"endOffset": 47,
"name": "commentor",
"text": "ich"
},
{
"beginOffset": 48,
"endOffset": 55,
"name": "negation",
"text": "nicht ."
}
],
"text": " Weitere Aspekte der Kommission kommentiere ich nicht . ",
"verb": {
"beginOffset": -1,
"endOffset": -1,
"sense": "COMMENT, intransitive",
"text": "kommentieren"
}
}
],
"verb": "KOMMENTIEREN"
}
]
Change all of your references to
obj[t].tgtLanguageSentences[t].roles[t]
to
obj[0].tgtLanguageSentences[0].roles[t]
here is the problem:
In below snippet code you are looping through the role but in substring you passing obj[t].
As per above given JSON you have only one item in obj however in role you have more than 1 item.
for(var t=0; t<obj[0].tgtLanguageSentences[0].roles.length; t++)
{
// create variables representing substrings of the Source language Sentence
var tgt1 = text1.substring((obj[t].tgtLanguageSentences[t].roles[t].beginOffset - obj[t].tgtLanguageSentences[t].roles[t].beginOffset),(obj[t].tgtLanguageSentences[t].roles[t].beginOffset - 1));
var tgt2 = text1.substring(obj[t].tgtLanguageSentences[t].roles[t].beginOffset,obj[t].tgtLanguageSentences[t].roles[t].endOffset);
var tgt3 =
text1.substring(obj[t].tgtLanguageSentences[t].roles[t].endOffset,obj[t].tgtLanguageSentences[t].text.length);
Answere is:
var tgt1 = text1.substring((obj[0].tgtLanguageSentences[0].roles[t].beginOffset - obj[0].tgtLanguageSentences[0].roles[t].beginOffset),(obj[0].tgtLanguageSentences[0].roles[t].beginOffset - 1));
Hope this will help you :)
Would be helpful to know, from debugging, which line is throwing the error. But it's probably this one:
var tgt1 = text1.substring((obj[t].tgtLanguageSentences[t].roles[t].beginOffset - obj[t].tgtLanguageSentences[t].roles[t].beginOffset),(obj[t].tgtLanguageSentences[t].roles[t].beginOffset - 1));
Using t to index obj and tgtLAnguageSentences and roles is problematic based on your JSON object example. The loop will run 4 times based on t<obj[0].tgtLanguageSentences[0].roles.length.
When t = 1, for instance, you are trying to find a value at obj[1].tgtLanguageSentences[1].roles[1] if there is no object at obj[1].tgtLanguageSentences[1] then you will get "cannot read property 'roles' of undefined."

Categories

Resources