Using jQuery to get JSON Data - javascript

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 ;
}

Related

Remove a sub level of an array

I get a list of items with add-ons from the server, but when I try to delete an add-on from this list I can't. I noticed that when I try to access the property grupoAdicionais.produto.codigo, it does not exist because it has a sublevel coming from the API, how do I remove this to have access to my product.codigo?
Array received from API:
"grupoAdicionais":[
{"produto": {"codigo":21, "descricao":"Bacon"}, "item":148657, "quantidade":1, "total":5},
{"produto": {"codigo":13193, "descricao":"Queijo"}, "item":148657, "quantidade":1, "total":1}
]
My code in the reducer to return the list without the extra:
REMOVER_ADICIONAL: (state, action) => {
let itemRemover = action.item;
let listaReducer = state.lstItensRestauranteQRcode;
const itemRemovido = listaReducer.filter((item) => {
return item.grupoAdicionais.produto.codigo != itemRemover.produto.codigo;
});
state.lstItensRestauranteQRcode = itemRemovido;
},
If all you want to do is get a list of the codes:
const response = {"grupoAdicionais": [{
"produto": {
"codigo": 21,
"descricao": "Bacon"
},
"item": 148657,
"quantidade": 1,
"total": 5
}, {
"produto": {
"codigo": 13193,
"descricao": "Queijo"
},
"item": 148657,
"quantidade": 1,
"total": 1
}]}
const codigos = response.grupoAdicionais.map(grupo => grupo.produto.codigo)
console.log(codigos)
// =>
[ 21, 13193 ]
I'm not totally sure, but it seems like maybe you want to remove a group by its code.
const removeByCode = (code) => response.grupoAdicionais.filter((group) => group.produto.codigo !== code)
const newGroups = removeByCode(21)
console.log(newGroups)
// =>
[
{
produto: { codigo: 13193, descricao: 'Queijo' },
item: 148657,
quantidade: 1,
total: 1
}
]
var response = {"grupoAdicionais": [{
"produto": {
"codigo": 21,
"descricao": "Bacon"
},
"item": 148657,
"quantidade": 1,
"total": 5
}, {
"produto": {
"codigo": 13193,
"descricao": "Queijo"
},
"item": 148657,
"quantidade": 1,
"total": 1
}]}
console.dir(response.grupoAdicionais[0].produto.codigo)
grupoAdicionais is an array here, you have to access it like this:
console.dir(response.grupoAdicionais[0].produto.codigo)

How to get distinct value from an array of objects containing array

I am trying to get an array of distinct values from the data structure below. I tried using reduce and object keys with no luck. What can I try next?
Data:
var data = [{
"id": 1,
"Technologies": ["SharePoint", "PowerApps"]
},
{
"id": 2,
"Technologies": ["SharePoint", "PowerApps", "SomethingElse"]
},
{
"id": 3,
"Technologies": ["SharePoint"]
},
{
"id": 4,
"Technologies": ["PowerApps"]
},
{
"id": 5,
"Technologies": null
}
]
Finished result should look like:
var distintValues = ["PowerApps", "SharePoint", "SomethingElse", null]
My attempt:
https://codepen.io/bkdigital/pen/MWEoLXv?editors=0012
You could use .flatMap() with a Set. .flatMap allows you to map each object's technology to one resulting array, and the Set allows you to remove the duplicates. With the help of optional chaining ?., you can also keep the null value (so it doesn't throw when accessing Technologies) like so:
const data = [{ "id": 1, "Technologies": ["SharePoint", "PowerApps"] }, { "id": 2, "Technologies": ["SharePoint", "PowerApps", "SomethingElse"] }, { "id": 3, "Technologies": ["SharePoint"] }, { "id": 4, "Technologies": ["PowerApps"] }, { "id": 5, "Technologies": null } ];
const res = [...new Set(data.flatMap(obj => obj?.Technologies))];
console.log(res);
[...new Set(
data
.map(v => Array.isArray(v.Technologies) ? v.Technologies : [v.Technologies])
.reduce((t, v) => [...t, ...v], [])
)];
I tried to solve this through JS. Here is my code:
const data = [{
"id": 1,
"Technologies": ["SharePoint", "PowerApps"]
}, {
"id": 2,
"Technologies": ["SharePoint", "PowerApps", "SomethingElse"]
}, {
"id": 3,
"Technologies": ["SharePoint"]
}, {
"id": 4,
"Technologies": ["PowerApps"]
}, {
"id": 5,
"Technologies": null
}]
const distintValues = [];
for (let element of data) {
if (element.Technologies != null) {
for (let elem of element.Technologies) {
if (!distintValues.includes(elem)) {
distintValues.push(elem);
}
}
}
}
console.log(distintValues);
In your attempt you tried to do it with reduce so here is how I would do it
var data = [{
"id": 1,
"Technologies": ["SharePoint", "PowerApps"]
},
{
"id": 2,
"Technologies": ["SharePoint", "PowerApps", "SomethingElse"]
},
{
"id": 3,
"Technologies": ["SharePoint"]
},
{
"id": 4,
"Technologies": ["PowerApps"]
},
{
"id": 5,
"Technologies": null
}
];
const objAsArray = Object.keys(data) // first we get the keys
.map(key => data[key]) // then we map them to their value
const technologyMap = objAsArray.reduce((acc, data) => {
// if the entry has technologies we set the key in the accumulation object to true
if (data.Technologies) {
data.Technologies.forEach(tech => acc[tech] = true)
}
return acc;
}, {})
// at the very end we get the keys of the accumulation object
const uniqueTechnologies =
Object.keys(
technologyMap
)

Javascript JSON file filter with object as a parameter

I'm a newbie in Javascript and I'm trying to understand the destructuring approach also with object literals. So what I'm trying to do is to create a function which has two types of arguments: 1. It's a JSON data file which I want to iterate. 2. An object literal with a random value assigned. So I'm trying to iterate with this object value passed as a parameter and filter with the data from the JSON file with an if statement inside the array of objects iterator. And add to arr all the object which match.
Thanks everyone in advance.
Array of objects:
[
{ "id": 44, "hours": 100,"finished": false },
{ "id": 22, "hours": 80,"finished": false },
{ "id": 65, "hours": 34,"finished": false },
{ "id": 1098, "hours": 21,"finished": true },
{ "id": 2, "hours": 67,"finished": false },
{ "id": 765, "hours": 32,"finished": false },
{ "id": 223, "hours": 555,"finished": false },
{ "id": 986, "hours": 2,"finished": false }
]
main.js
const data = require('./example.json')
function dataFilter (items, {id: _id, hours: _hours, finished: _finished}) {
for (let i = 0; i < items.length; i++) {
let arr = [];
if (items[i].id === _id) {
arr.push(items[i])
}
else if (items[i].hours >= _hours){
arr.push(items[i])
}
else if (items[i].finished === finished){
arr.push(items[i])
}
return arr;
}
}
console.log(dataFilter(data,{ id: 65 }));
console.log(dataFilter(data,{ hours: 30 }));
You don't need destructuring, what you need is array filter.
You also forgot to set a default {} so you can access undefined keys:
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/filter
const data = [
{ "id": 44, "hours": 100,"finished": false },
{ "id": 22, "hours": 80,"finished": false },
{ "id": 65, "hours": 34,"finished": false },
{ "id": 1098, "hours": 21,"finished": true },
{ "id": 2, "hours": 67,"finished": false },
{ "id": 765, "hours": 32,"finished": false },
{ "id": 223, "hours": 555,"finished": false },
{ "id": 986, "hours": 2,"finished": false },
{ "id": 1986, "hours": 30,"finished": false },
];
function dataFilter (items, {id: _id, hours: _hours, finished: _finished} = {}) {
return items.filter((item) => item.id === _id || item.hours >= _hours || item.finished === _finished);
}
document.getElementById('results').innerHTML = `
<pre>
ID: 65
${JSON.stringify(dataFilter(data,{ id: 65 }), null, 2)}
HOURS: 30
${JSON.stringify(dataFilter(data,{ hours: 30 }), null, 2)}
</pre>
`
<div id="results"></div>
Approach with multiple filters
It is also possible to use more than one filter at once:
const data = [
{ "id": 44, "hours": 100,"finished": false },
{ "id": 22, "hours": 80,"finished": false },
{ "id": 65, "hours": 34,"finished": false },
{ "id": 1098, "hours": 21,"finished": true },
{ "id": 2, "hours": 67,"finished": false },
{ "id": 765, "hours": 32,"finished": false },
{ "id": 223, "hours": 555,"finished": false },
{ "id": 986, "hours": 2,"finished": false },
{ "id": 1986, "hours": 30,"finished": false },
];
function dataFilter (items, filters = {}) {
// this will create a list of function on the fly for every `filters` you pass.
const fnList = Object.keys(filters)
.map((key) => (list) => list.filter((item) => item[key] === filters[key]));
let res = [...items];
while (cursor = fnList.shift()) {
res = cursor(res);
}
return res;
}
document.getElementById('results').innerHTML = `
<pre>
ID: 44, HOURS: 100
${JSON.stringify(dataFilter(data,{ id: 44, hours: 100 }), null, 2)}
ID: 2, HOURS: 67
${JSON.stringify(dataFilter(data,{ id: 2 }), null, 2)}
</pre>
`
<div id="results"></div>
If you want to specify the operators used for the comparaison, use a fonction as explained here: Are Variable Operators Possible?
Looks like you want to be able to filter the data by any combination of the three items in that object.
function filterFactory({id, hours, finished}) {
return function filter(item) {
let isGoodValue = false;
if (id !== undefined && item.id === id) isGoodValue = true;
// for the second and third checks we'll short-circuit if it already
// passed an earlier check
if (!isGoodValue && hours !== undefined && item.hours >= hours) isGoodValue = true;
if (!isGoodValue && finished !== undefined && item.finished === finished) isGoodValue = true;
return isGoodValue;
};
}
data.filter(filterFactory({id: 2}));
Note that we're using the native filter method on arrays. filterFactory is a factory that makes callbacks to pass to filter based on one or more of the three factors you're filtering on.

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");`

How to get information from too array json in AngularJS

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>

Categories

Resources