2016-01-12 271 views
0

我有以下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 
    }; 
}); 

但它的不工作

回答

1

您需要得到第一個元素Arrayfruit.prices[0].small因爲fruit.pricesArray只包含一個元素,這個元素是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可以ObjectArray與that't爲什麼例如有狀態檢查它(Array.isArray

一種元素