简体   繁体   English

如何映射嵌套对象的数组?

[英]How to map an array of nested objects?

I have the following JSON response: 我有以下JSON响应:

{
    "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: 我想将其映射到一个新数组,以便获得每个水果的“ price.small”:

$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 您需要在Array fruit.prices[0].small获得第一个元素,因为fruit.prices是仅包含一个元素且该元素为Object Array

 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 ) fruit.prices可以是具有一个元素的ObjectArray ,这就是为什么在示例中没有条件对其进行检查的原因( Array.isArray

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM