trs
trs

Reputation: 863

How to map an array of nested objects?

I have the following JSON response:

{
    "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:

$scope.new_data = $scope.fruits.map(function(fruit){
    return {
        name: fruit.name,
        price_small: fruit.prices.small
    };
});

But it's not working

Upvotes: 0

Views: 74

Answers (1)

Oleksandr T.
Oleksandr T.

Reputation: 77512

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

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)

Upvotes: 1

Related Questions