Reputation: 33
I have a long font data array, more than 100 elements like this :
var fonts = [
{
"id": 1,
"name": "Arial",
"set": 1
},
{
"id": 3,
"name": "Aller",
"set": 1
},
{
"id": 4,
"name": "Amatic",
"set": 0
},
{
"id": 5,
"name": "Architects Daughter",
"set": 0
},
{
"id": 6,
"name": "Black Jack",
"set": 0
}
]
Now I want to refine my array like this (new array containing only name
data)
fonts = [
"Arial",
"Aller",
"Amatic",
"Architects Daughter",
"Black Jack"
]
I can do it by :
var _tempArray;
$.each(fonts,function(){
_tempArray.push($(this).name);
});
fonts = _tempArray;
But I know it is not the nifty solution. What can I do for better?
Upvotes: 2
Views: 72
Reputation: 27853
map is perfect for this:
var names = fonts.map(function(item) { return item.name });
Upvotes: 3
Reputation: 239693
You can use $.map
function, like this
fonts = $.map(fonts, function(val) {
return val.name;
});
If your browser supports Array.prototype.map
, you can use
fonts = fonts.map(function(val) {
return val.name;
});
Upvotes: 2