gudthing gudthing - 4 months ago 24
Javascript Question

Extract Javascript data using map(), filter() and concatAll() functions

The output is almost correct, but I am having trouble flattening the nested boxart array.

Javascript data:

var movieLists = {
name: "Instant Queue",
videos : [
{
"id": 70111470,
"title": "Die Hard",
"boxarts": [
{width: 150, height:200, url:"http://cdn-0.nflximg.com/images/2891/DieHard150.jpg"},
{width: 200, height:200, url:"http://cdn-0.nflximg.com/images/2891/DieHard200.jpg"}
],
"url": "http://api.netflix.com/catalog/titles/movies/70111470",
"rating": 4.0,
"bookmark": [{ id:432534, time:65876586 }]
},
{
"id": 654356453,
"title": ....,
}];


Expected Output: (using only the functions
.map()
,
.filter()
,
.concatAll()
, return id, title, boxart:url of films which have the boxart image dimensions 150x200

// [
// {"id": 675465,"title": "Fracture","boxart":"http://cdn-0...." },
// {"id": 65432445,"title": "The Chamber","boxart":"http://cdn-0...." },
// {"id": 654356453,...}
// ];


Current Output:

// [ //boxart value is an array
// {"id": 675465,"title": "Fracture","boxart":["http://cdn-0...."]},
// {"id": 65432445,"title": "The Chamber","boxart":["http://cdn-0...."]},
// {"id": 654356453,...}
// ];


My Solution:

return movieLists.map(function (category) {
return category.videos.map(function (video) {
return {
id: video.id,
title: video.title,
boxart: video.boxarts.filter(function (boxartFeature) {
return boxartFeature.width === 150 && boxartFeature.height === 200;
})
.map(function (boxartProp) {
return boxartProp.url;
})
};
});
}).concatAll(); //Flattens nested array by 1 dimension (please see demo)


I know I need to apply the
.concatAll()
function to remove the nested boxart array, but I can't seem to find the place where.

Please click here for demo

Answer

map returns an array. You are storing the result of map in the boxart property.

If you don't want to store an array in boxart, simply store the first member (index 0) of the array instead:

//...
.map(function (boxartProp) {
     return boxartProp.url;
})[0]
Comments