0

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

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.