1

I have the following data:

{
    "fruits": [
        {
            "name": "apple",
            "prices": [
                {
                    "2015": 2,
                    "2014": 3,
                    "2013": 1
                }
            ]
        },
        {
            "name": "banana",
            "prices": [
                {
                    "2015": 4,
                    "2014": 1,
                    "2013": 3
                }
            ]
        }
    ]
}

In my .js file, inside my controller, I want to calculate the difference between the price of the latest year and the year before.

Such as:

Apples = 3 - 2 = -1

So that in my HTML I can do:

<div ng-repeat="fruit in fruits">
    {{fruit.name}}, {{fruit.change}}
</div>

I've tried the following with no luck:

angular.forEach($scope.fruits, function(fruit, key) {
    angular.forEach(fruit.prices, function(price, key) {
        this.change = price[0] - price[1];
    });
});
6
  • i think you can doing it inside the view page bring the two values from controller and calculate it Commented Jan 8, 2016 at 15:41
  • is your data populated by a http call in a factory or is it something else like static json or firebase? Commented Jan 8, 2016 at 15:47
  • 1
    @JoeLloyd Kind of besides the point… Commented Jan 8, 2016 at 15:53
  • @ElieMA No, I need it in the .js file Commented Jan 8, 2016 at 15:54
  • @JoeLloyd Yes, correct Commented Jan 8, 2016 at 16:00

1 Answer 1

1

Just a typo, instead of this use fruit and it'll work.

function calculate(targetYear){
    angular.forEach($scope.fruits, function(fruit, key) {
        $scope.fruits[key].change = fruit.prices[0][targetYear] - fruit.prices[0][targetYear-1];
    });
}

You can use this function like: calculate(2015) and it'll set for each fruit.change value to show the change between 2015/2014

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

5 Comments

reason for downvoting?
The prices are objects, they don't have keys called 0 or 1.
@Juhana How do you get the 0 and 1 of prices?
@murid They don't have such keys. Objects are unordered. If you want to find the key with the highest value, you have to first get the keys, sort them, and then pick the first one.
Changed. Try it now pls

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.