如何映射嵌套对象数组?

时间:2016-01-12 12:11:07

标签: javascript arrays

我有以下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 个答案:

答案 0 :(得分:1)

您需要获取Array fruit.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,其中一个元素不是为什么在例子中有条件来检查它(Array.isArray