2016-01-12 5 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.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 с одним элементом that't почему в примере есть условие, чтобы проверить его (Array.isArray)

Смежные вопросы