Aurelia - repeat.for json - javascript

I am new to Aurelia.
I'm trying to iterate (repeat.for) through some json that looks like below. I am able to do so with a manual concat but the number of artists is variable. Below for example works.
return this.http.fetch(baseUrl + "/artists/" + token + "&search=" + searchCreator)
.then(response => response.json())
.then(response => {
//for (var i = 0; i < response.resultsCount; i++){
// response += response.artists[i].objects;
//}
return response.artists[0].objects.concat(response.artists[1].objects);
});
How can I return all objects for all artists? I've tried doing this with a for loop but I can't get it to work. Should I return response.artists and then work with that in my view model? This is what the view looks like:
<tr repeat.for="item of items">
<td>${item.title}</td>
<td>${item.displayName}</td>
<td>${item.objectNumber}</td>
</tr>
json example:
{
"source": "My Museum",
"language": "EN",
"resultsCount": ​58,
"artists":
[{
"artistID": ​47171,
"alphaSort": "Smith Eloise Vega",
"displayName": "Eloise Vega Smith",
"beginDate": "0",
"endDate": "0",
"displayDate": "",
"sex": "Female",
"nationality": "",
"objectCount": ​1,
"objects":
[{
"objectNumber": "209.2015",
"objectID": ​188963,
"title": "Album cover for Urszula Dudziak, Newborn Light",
"displayName": "Eloise Vega Smith",
"alphaSort": "Smith Eloise Vega",
"artistID": ​47171,
"displayDate": "",
"dated": "1974",
"dateBegin": ​1974,
"dateEnd": ​1974,
"medium": "Lithograph",
"dimensions": "12 1/2 x 12 1/4\" (31.8 x 31.1 cm)",
"department": "Architecture & Design",
"classification": "A&D Graphic Design",
"onView": ​0,
"provenance": "",
"description": "",
"objectStatusID": ​1,
"creditLine": "Committee on Architecture and Design Funds",
"imageID": "502407",
"thumbnail": "http:///TMSImages/Size1/Images/TR15211_10_RICR.jpg",
"fullImage": "http:///TMSImages/Size3/Images/TR15211_10_RICR.jpg",
"lastModifiedDate": "2015-09-17T01:00:08"
}
]
},
{
"artistID": ​5479,
"alphaSort": "Smith Charles",
"displayName": "Charles Smith",
"beginDate": "1893",
"endDate": "1987",
"displayDate": "American, 1893–1987",
"sex": "Male",
"nationality": "American",
"objectCount": ​6,
"objects":
[{
"objectNumber": "369.1941",
"objectID": ​67911,
"title": "Red Circle",
"displayName": "Charles Smith",
"alphaSort": "Smith Charles",
"artistID": ​5479,
"displayDate": "American, 1893–1987",
"dated": "1940",
"dateBegin": ​1940,
"dateEnd": ​1940,
"medium": "Monoprint",
"dimensions": "Sheet 21 1/8 x 14 3/4\" (53.8 x 37.5 cm) Comp. 20 x 14 3/4\" (50.8 x 37.5 cm)",
"department": "Prints & Illustrated Books",
"classification": "Print",
"onView": ​0,
"provenance": "",
"description": "Color monoprint, printed from movable forms",
"objectStatusID": ​1,
"creditLine": "Purchase",
"imageID": "260293",
"thumbnail": "http:///TMSImages/Size1/Images/369_1941_RICR.jpg",
"fullImage": "http:///TMSImages/Size3/Images/369_1941_RICR.jpg",
"lastModifiedDate": "2015-03-31T01:06:18"
},
{
"objectNumber": "214.1942",
"objectID": ​64517,
"title": "Abstraction",
"displayName": "Charles Smith",
"alphaSort": "Smith Charles",
"artistID": ​5479,
"displayDate": "American, 1893–1987",
"dated": "c. 1942",
"dateBegin": ​1942,
"dateEnd": ​1942,
"medium": "Woodcut",
"dimensions": "composition (irreg.): 11 1/4 x 3 3/4\" (28.5 x 9.6 cm); sheet: 14 9/16 x 7 1/16\" (37 x 17.9 cm)",
"department": "Prints & Illustrated Books",
"classification": "Print",
"onView": ​0,
"provenance": "",
"description": "Woodcut, printed in black, dark green yellow, deep blue and strong red brown",
"objectStatusID": ​1,
"creditLine": "Given anonymously",
"imageID": "195213",
"thumbnail": "http:///TMSImages/Size1/Images/214_1942_RICR.jpg",
"fullImage": "http:///TMSImages/Size3/Images/214_1942_RICR.jpg",
"lastModifiedDate": "2014-09-19T01:05:22"
},
etc.....
I appreciate the help!

If you are familiar with LINQ, you could use a library like jslinq and do the following:
return jslinq(response.artists)
.selectMany(function(artist){
return artist.objects
}).toList();
of course I would only include jslinq if I planned to use it more than once in the project. If you don't want the overhead, your solution with concat should work just fine:
var result = [];
for(var i = 0; i < response.artists.length; i++) {
result = result.concat(response.artists[i].objects);
}
return result;

Related

Fetch and parse multiple arrays from .json file

I'm making a collection of all the movies I've watched and I keep all my data in movies.json. In movies.json there are multiple arrays, the first one being "MarvelMovies" with 2 movies in.
Next is "ComedyMovies" with also 4 movies.
I can console.log all the arrays, but I haven't figured out how to console.log each array (console.log the MarvelMovies array and ComedyMovies separately).
movies.json:
{
"MarvelMovies": [{
"Title": "The Avengers",
"Year": "2012",
"Poster": "https://m.media-amazon.com/images/M/MV5BNDYxNjQyMjAtNTdiOS00NGYwLWFmNTAtNThmYjU5ZGI2YTI1XkEyXkFqcGdeQXVyMTMxODk2OTU#._V1_SX300.jpg",
"Ratings": [{
"Source": "Internet Movie Database",
"Value": "8.0/10"
}, {
"Source": "Rotten Tomatoes",
"Value": "91%"
}, {
"Source": "Metacritic",
"Value": "69/100"
}],
"Metascore": "69"
}, {
"Title": "Avengers: Age of Ultron",
"Year": "2015",
"Rated": "PG-13",
"Released": "01 May 2015",
"Runtime": "141 min",
"Genre": "Action, Adventure, Sci-Fi",
"Director": "Joss Whedon",
"Writer": "Joss Whedon, Stan Lee (based on the Marvel comics by), Jack Kirby (based on the Marvel comics by), Joe Simon (character created by: Captain America), Jack Kirby (character created by: Captain America), Jim Starlin (character created by: Thanos)",
"Actors": "Robert Downey Jr., Chris Hemsworth, Mark Ruffalo, Chris Evans",
"Plot": "When Tony Stark and Bruce Banner try to jump-start a dormant peacekeeping program called Ultron, things go horribly wrong and it's up to Earth's mightiest heroes to stop the villainous Ultron from enacting his terrible plan.",
"Language": "English, Korean",
"Country": "USA",
"Awards": "8 wins & 49 nominations.",
"Poster": "https://m.media-amazon.com/images/M/MV5BMTM4OGJmNWMtOTM4Ni00NTE3LTg3MDItZmQxYjc4N2JhNmUxXkEyXkFqcGdeQXVyNTgzMDMzMTg#._V1_SX300.jpg",
"Ratings": [{
"Source": "Internet Movie Database",
"Value": "7.3/10"
}, {
"Source": "Rotten Tomatoes",
"Value": "75%"
}, {
"Source": "Metacritic",
"Value": "66/100"
}],
"Metascore": "66",
"imdbRating": "7.3",
"imdbVotes": "759,059",
"imdbID": "tt2395427",
"Type": "movie",
"DVD": "08 Sep 2015",
"BoxOffice": "$459,005,868",
"Production": "Marvel Studios",
"Website": "N/A",
"Response": "True"
}
],
"ComedyMovies": [{
"Title": "The Avengers",
"Year": "2012",
"Poster": "https://m.media-amazon.com/images/M/MV5BNDYxNjQyMjAtNTdiOS00NGYwLWFmNTAtNThmYjU5ZGI2YTI1XkEyXkFqcGdeQXVyMTMxODk2OTU#._V1_SX300.jpg",
"Ratings": [{
"Source": "Internet Movie Database",
"Value": "8.0/10"
}, {
"Source": "Rotten Tomatoes",
"Value": "91%"
}, {
"Source": "Metacritic",
"Value": "69/100"
}],
"Metascore": "69"
}, {
"Title": "Avengers: Age of Ultron",
"Year": "2015",
"Rated": "PG-13",
"Released": "01 May 2015",
"Runtime": "141 min",
"Genre": "Action, Adventure, Sci-Fi",
"Director": "Joss Whedon",
"Writer": "Joss Whedon, Stan Lee (based on the Marvel comics by), Jack Kirby (based on the Marvel comics by), Joe Simon (character created by: Captain America), Jack Kirby (character created by: Captain America), Jim Starlin (character created by: Thanos)",
"Actors": "Robert Downey Jr., Chris Hemsworth, Mark Ruffalo, Chris Evans",
"Plot": "When Tony Stark and Bruce Banner try to jump-start a dormant peacekeeping program called Ultron, things go horribly wrong and it's up to Earth's mightiest heroes to stop the villainous Ultron from enacting his terrible plan.",
"Language": "English, Korean",
"Country": "USA",
"Awards": "8 wins & 49 nominations.",
"Poster": "https://m.media-amazon.com/images/M/MV5BMTM4OGJmNWMtOTM4Ni00NTE3LTg3MDItZmQxYjc4N2JhNmUxXkEyXkFqcGdeQXVyNTgzMDMzMTg#._V1_SX300.jpg",
"Ratings": [{
"Source": "Internet Movie Database",
"Value": "7.3/10"
}, {
"Source": "Rotten Tomatoes",
"Value": "75%"
}, {
"Source": "Metacritic",
"Value": "66/100"
}],
"Metascore": "66",
"imdbRating": "7.3",
"imdbVotes": "759,059",
"imdbID": "tt2395427",
"Type": "movie",
"DVD": "08 Sep 2015",
"BoxOffice": "$459,005,868",
"Production": "Marvel Studios",
"Website": "N/A",
"Response": "True"
}
]
}
my js fetch code:
//DOM element
let movieSlider = document.querySelector(".mainSlider") //Grid til film
let movieTitle = document.querySelector(".mainSlider__title"); //genre titel
fetch('./media/json/movies.json')
.then(response => response.json())
.then((movies) => {
console.log(movies)
// console.log(response);
// });
// .then(movie => {
for (let i = 0; i < movies.length; i++) {
const element = movies[i];
movieSlider.innerHTML += `
<div class="mainSlider__item" style='background:url("${element.Poster}"); background-size:cover;'>
<div class="mainSlider__item-playButton">
<div class="mainSlider__item-title">${element.Title}</div>
<div class="mainSlider__item-info">${element.Year}</div>
<div class="mainSlider__item-desc">${element.Runtime}</div>
</div>
</div>
`
}
});
If you don't know the property names and also you don't need them. (They seem like categories). You can use Object.values and Array.flat methods to retrieve an array that contains just movies like below :
const json = `your json`
const movies = Object.values(json).flat();
console.log(movies);
const json = `your json`
const movies = Object.values(json).flat();
console.log(movies);

How to sort an array of object based on number and string (Arabic names)?

Here is my snippet which has names in Arabic (i.e I want to show some data for Saudi Arabia)
I have tried local compare() method but doesn't work
let arr = [{
"id": "4231a075-ac9d-4c58-b6c2-2d4cf73d72e1",
"name": "النَّشاطُ الثّالِثُ - وَرْشَةُ الْكِتابَةِ 2",
"author": "na",
"countryCode": "SA",
"createdAt": "2019-10-06T07:30:16.770Z",
"pageId": "188"
},
{
"id": "fde7d816-4eb8-4c82-a875-23hsd",
"name": "النَّشاطُ الثّاني - وَرْشَةُ الْكِتابَةِ 1",
"author": "na",
"countryCode": "SA",
"createdAt": "2019-10-06T07:30:16.770Z",
"pageId": "188"
}
]
arr.sort(function(a, b) {
return a.pageId - b.pageId || a.name.localeCompare(b.name, ["ar"]);
});
console.log(arr)
It seems that the numbers you entered with the Arabic text are not proper Arabic encoded. Now seems all fine and sorts properly.
let arr = [{
"id": "4231a075-ac9d-4c58-b6c2-2d4cf73d72e1",
"name": "2 النَّشاطُ الثّالِثُ - وَرْشَةُ الْكِتابَةِ",
"author": "na",
"countryCode": "SA",
"createdAt": "2019-10-06T07:30:16.770Z",
"pageId": "188"
},
{
"id": "fde7d816-4eb8-4c82-a875-23hsd",
"name": "1 النَّشاطُ الثّاني - وَرْشَةُ الْكِتابَةِ",
"author": "na",
"countryCode": "SA",
"createdAt": "2019-10-06T07:30:16.770Z",
"pageId": "188"
}
]
arr.sort(function(a, b) {
return a.pageId - b.pageId || a.name.localeCompare(b.name, ["ar"]);
});
console.log(arr)

access javascript value within the <script> tag with xpath

from this tag:
<script type = "text/javascript" > dataLayer.push({
"pageType": "productPage", "ecommerce": {
"currencyCode": "EUR",
"detail": {
"actionField": {"list": "Detail", "action": "detail"},
"products": [{
"name": "Desodorante Spray Alien",
"id": "10483558",
"price": "34,95",
"brand": "MUGLER",
"category": "higiene\/desodorantes",
"variant": "100 ML",
"dimension5": "Mucho stock",
"dimension6": "Unisex",
"dimension7": "CLARINS SPAIN, S.A",
"dimension8": "No",
"dimension9": "",
"metric2": 1
}]
},
"impressions": [{
"name": "Angel men recarga Eau de Toilette",
"id": "10059432",
"price": "47.95",
"brand": "MUGLER",
"category": "perfumes_hombre_edt",
"variant": "100 ML ",
"list": "you may want",
"position": 1
}, {
"name": "Angel men rubber flask Eau de Toilette",
"id": "10351154",
"price": "42.95",
"brand": "MUGLER",
"category": "perfumes_hombre_edt",
"variant": "50 ML ",
"list": "you may want",
"position": 2
}, {
"name": "Alien Shower Milk",
"id": "10483565",
"price": "26.00",
"brand": "MUGLER",
"category": "higiene_geles",
"variant": "200 ML ",
"list": "you may want",
"position": 3
}, {
"name": "Amen Desodorante en Stick",
"id": "10532706",
"price": "21.95",
"brand": "MUGLER",
"category": "hombre_desodorantes",
"variant": "75 ML ",
"list": "you may want",
"position": 4
}]
}
});
(window["rrApiOnReady"] = window["rrApiOnReady"] || []).push(function () {
retailrocket.productsGroup.post({
"groupId": 10483558,
"name": "Desodorante Spray Alien",
"price": 34.95,
"pictureUrl": "https://ima.douglas.es/img/1467/desodorante_spray_alien-0-.png",
"url": "https://douglas.es/p/mugler/desodorante_spray_alien",
"isAvailable": true,
"categoryPaths": ["Higiene/Corporal", "Corporal", "Corporal/Higiene", "Higiene", "Higiene/Desodorante", "Marca/Mugler"],
"description": "El elixir de feminidad y de sensualidad del Eau de Parfum Alien en su versión desodorante en spray. Déjate envolver con los mismos acordes de la fragancia.",
"vendor": "MUGLER",
"products": {
"10483558": {
"isAvailable": true,
"name": "Desodorante Spray Alien",
"size": "100",
"url": "https://douglas.es/p/mugler/desodorante_spray_alien",
"pictureUrl": "https://ima.douglas.es/img/1467/desodorante_spray_alien-0-.png",
"price": 34.95,
"oldPrice": 34.95,
"params": {}
}
},
"params": {"medida": "ML", "subTitle": "Todo tipo de piel"},
"model": "Desodorante Spray Alien",
"typePrefix": "higiene_desodorantes",
"oldPrice": 34.95
});
rrApi.groupView([10483558]);
});
App.page.webshop = "DOU";
App.page.warehouse = ["ALM"];
App.page.codPostal = "";
</script>
I need to access some specific values of different functions (products, products.brand, impressions and impressions.id).
I tried to convert it to json dictionary, but it is a list and it gets converted into an array and I cannot access it with a "name" value.
How can I do this?
An example would be to select the script using some unique keyword which is only present in this script. Once you have that, you can use re_first to get the desired value. Take this as an example:
product_css = "script:contains('productPage')::text"
regex = 'name": "(.+?)"'
product_name = response.css(product_count_css).re_first(regex)
This will extract the first name. You can use re to tweak it further. Best of luck.

Accessing objects in arrays inside objects in Angular

I am having quite a hard time accessing data from an api call and having it shown on Mapbox. I am able to have one marker shown on the map, while I should have 10 markers. I think I am doing something wrong with ng-repeat, but I am not sure what. Any help would be appreciated.
Here is a link to view the full JSON response from the API call http://jsonblob.com/55e734cee4b01190df374f1e
// index.html
<div ng-repeat="venue in bars.venues">
<marker lat="{{venue.location.lat}}" lng="{{venue.location.lng}}">
<h1>{{venue.name}}</h1>
<p>{{venue.contact}}</p>
<p>{{venue.location.formattedAddress}}</p>
</marker>
</div>
// app.js
$http.get(url)
.then(function (response) {
$scope.bars = response.data.response;
});
// sample data from api
{
"meta": {
"code": 200,
"requestId": "55e72707498e3d9a002d7bc4"
},
"response": {
"venues": [
{
"id": "42c1e480f964a520c4251fe3",
"name": "The View",
"contact": {
"phone": "4158961600",
"formattedPhone": "(415) 896-1600"
},
"location": {
"address": "55 4th St",
"crossStreet": "at Marriott Marquis",
"lat": 37.78510950100554,
"lng": -122.40469515323639,
"distance": 29,
"postalCode": "94103",
"cc": "US",
"city": "San Francisco",
"state": "CA",
"country": "United States",
"formattedAddress": [
"55 4th St (at Marriott Marquis)",
"San Francisco, CA 94103",
"United States"
]
},
"categories": [
{
"id": "4bf58dd8d48988d1d5941735",
"name": "Hotel Bar",
"pluralName": "Hotel Bars",
"shortName": "Hotel Bar",
"icon": {
"prefix": "https://ss3.4sqi.net/img/categories_v2/travel/hotel_bar_",
"suffix": ".png"
},
"primary": true
}
],
"verified": false,
"stats": {
"checkinsCount": 12634,
"usersCount": 9499,
"tipCount": 121
},
"url": "http://www.sfviewlounge.com",
"hasMenu": true,
"menu": {
"type": "Menu",
"label": "Menu",
"anchor": "View Menu",
"url": "https://foursquare.com/v/the-view/42c1e480f964a520c4251fe3/menu",
"mobileUrl": "https://foursquare.com/v/42c1e480f964a520c4251fe3/device_menu"
},
So I figured out why only one marker was showing. I was previously using angular google maps and had ngMaps as a module. After I deleted it, all my markers showed.

jQuery .each display array data - cannot work it out

I'm trying to loop through all this array data but it won't work out how to display it all via jquery using the .each function? Can someone help me out?
ARRAY:
{
"ListOrdersResult": {
"Orders": {
"Order": [
{
"ShipmentServiceLevelCategory": "Standard",
"OrderTotal": {
"Amount": "29.00",
"CurrencyCode": "GBP"
},
"ShipServiceLevel": "Std UK Dom",
"LatestShipDate": "2013-11-28T23:59:59Z",
"MarketplaceId": "A1F83G8C2ARO7P",
"SalesChannel": "Amazon.co.uk",
"ShippingAddress": {
"Phone": "0800 000 0000",
"PostalCode": "A11 H11",
"Name": "stephanie ross",
"CountryCode": "GB",
"StateOrRegion": "regiion",
"AddressLine2": "cairnbulg",
"AddressLine1": "loco 2222 name",
"City": "fraserburgh"
},
"ShippedByAmazonTFM": "false",
"OrderType": "StandardOrder",
"FulfillmentChannel": "MFN",
"BuyerEmail": "c9tkdmn724jpgkd#blahblah.com",
"OrderStatus": "Shipped",
"BuyerName": "custom A Ross",
"LastUpdateDate": "2013-11-27T14:26:53Z",
"EarliestShipDate": "2013-11-27T00:00:00Z",
"PurchaseDate": "2013-11-26T22:25:39Z",
"NumberOfItemsUnshipped": "0",
"AmazonOrderId": "205-8108202-4976362",
"NumberOfItemsShipped": "1",
"PaymentMethod": "Other"
},
{
"ShipmentServiceLevelCategory": "Standard",
"OrderTotal": {
"Amount": "29.00",
"CurrencyCode": "GBP"
},
"ShipServiceLevel": "Std UK Dom",
"LatestShipDate": "2013-11-28T23:59:59Z",
"MarketplaceId": "A1F83G8C2ARO7P",
"SalesChannel": "Amazon.co.uk",
"ShippingAddress": {
"Phone": "0800 000 0000",
"PostalCode": "A11 H11",
"Name": "stephanie ross",
"CountryCode": "GB",
"StateOrRegion": "regiion",
"AddressLine2": "cairnbulg",
"AddressLine1": "loco 2222 name",
"City": "fraserburgh"
},
"ShippedByAmazonTFM": "false",
"OrderType": "StandardOrder",
"FulfillmentChannel": "MFN",
"BuyerEmail": "c9tkdmn724jpgkd#blahblah.com",
"OrderStatus": "Shipped",
"BuyerName": "custom A Ross",
"LastUpdateDate": "2013-11-27T14:26:53Z",
"EarliestShipDate": "2013-11-27T00:00:00Z",
"PurchaseDate": "2013-11-26T22:25:39Z",
"NumberOfItemsUnshipped": "0",
"AmazonOrderId": "205-8108202-4976362",
"NumberOfItemsShipped": "1",
"PaymentMethod": "Other"
}
]
},
"CreatedBefore": "2014-05-14T01:12:05Z"
},
"ResponseMetadata": {
"RequestId": "46f5c980-91e6-44d3-bc9d-668976855862"
},
"xmlns": "https://mws.amazonservices.com/Orders/2011-01-01"
}
CURRENT JS:
$(document).ready(function(){
$.get('functions/ListOrders.php', function(xml){
var newOrders = $.xml2json(xml);
$.each(newOrders.Orders.Order, function(index, value) {
console.log(value);
console.log(value.ShipmentServiceLevelCategory);
});
$('body').text(JSON.stringify(newOrders));
});
});
You are missing the first element of the JSON object:
Change
$.each(newOrders.Orders.Order, function(index, value) {
To
$.each(newOrders.ListOrdersResult.Orders.Order, function(index, value) {
Demo:
http://jsfiddle.net/9YU3H/

Categories