我有以下JSON响应:
{
"fruits": [
{
"name": "apple",
"prices": [
{
"small": 2,
"medium": 3,
"large": 5
}
]
},
{
"name": "banana",
"prices": [
{
"small": 1,
"medium": 3,
"large": 4
}
]
}
]
}
我想将它映射到一个新数组,以便我可以得到" price.small"每种水果:
$scope.new_data = $scope.fruits.map(function(fruit){
return {
name: fruit.name,
price_small: fruit.prices.small
};
});
但它不能正常工作
答案 0 :(得分:1)
您需要获取Array
fruit.prices[0].small
中的第一个元素,因为fruit.prices
是Array
,其中只包含一个元素且此元素为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);
更新:
fruit.prices
可以是Object
或Array
,其中一个元素不是为什么在例子中有条件来检查它(Array.isArray
)