Using Wikipedia's API I got an object which looks like that:
obj = {["string", Array[10], Array[10], Array[10]]}
The first array contains titles, second is descriptions and third is links.
Some of the descriptions may be empty ("").
Example -
I would like to combine all three arrays into one array as follow:
[{title: obj[1][0], desc: obj[2][0], link: obj[3][0]}, ... , {title: array[1][9], desc: obj[2][0], link: obj[3][0]}]
But only combining if description is not empty - obj[2][i] !== ""
I managed to do it using for loop and if:
var arr = [];
for (var i = 0; i < data[1].length; i++) {
if (data[2][i] !== '') {
arr.push({title: data[1][i], desc:data[2][i], link: data[3][i]});
}
}
Is there a way of achieving the same in a more elegant way using javascript's high order function? such as map
and filter
(maybe reduce
?)
Thanks
EDIT:
The way I did it in the end was:
var resp = ["Football",
['Football', 'Soccer'],
['FootballDescription', 'SoccerDescription'],
['http://football.com', 'http://soccer.com']
];
// Mimic python's zip behavior -> assume arrays are of equal size
function zip(arrays) {
return arrays[0].map(function(_, i){
return arrays.map(function(array){
return array[i];
});
});
}
// 1. Throw away the first string, e.g. "Football"
resp.shift();
// 2. Use zip to make an array of intersected arrays, i.e
// [
// ['Football', 'FootballDescription', 'http://football.com'],
// ['Soccer', 'SoccerDescription', 'http://soccer.com']
// ]
// and then use map to make each array into a nicely named object
var objects = zip(resp).map(function(x) {
return ({ name: x[0], desc: x[1], link: x[2] });
});
console.log(objects);
/*
Output:
[ { name: 'Football',
description: 'FootballDescription',
link: 'http://football.com' },
{ name: 'Soccer',
description: 'SoccerDescription',
link: 'http://soccer.com' } ]
*/