I have the following JSON response:
{
"fruits": [
{
"name": "apple",
"prices": [
{
"small": 2,
"medium": 3,
"large": 5
}
]
},
{
"name": "banana",
"prices": [
{
"small": 1,
"medium": 3,
"large": 4
}
]
}
]
}
I want to map it to a new array, so that I can get the "price.small" of each fruit:
$scope.new_data = $scope.fruits.map(function(fruit){
return {
name: fruit.name,
price_small: fruit.prices.small
};
});
But it's not working
You need get first element in Array
fruit.prices[0].small
because fruit.prices
is Array
that contains only one element and this element is Object
var $scope = {}; $scope.fruits = [{ "name": "apple", "prices": [{ "small": 2, "medium": 3, "large": 5 }] }, { "name": "banana", "prices": [{ "small": 1, "medium": 3, "large": 4 }] }, { "name": "mango", "prices": { "small": 100, "medium": 3, "large": 4 } }]; $scope.new_data = $scope.fruits.map(function(fruit){ return { name: fruit.name, price_small: Array.isArray(fruit.prices) ? fruit.prices[0].small : (fruit.prices || {}).small || 0 }; }); console.log($scope.new_data);
Update:
fruit.prices
can be Object
or Array
with one element that't why in example there is condition to check it ( Array.isArray
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.