1

What's the AngularJS way to get the value by key from the object?

var myobj=   {
        "set1": {
            "key": "B11",
            "color": "yellow"
        },
        "setA": {
            "key": "F34",
            "color": "green"
        }
    }

let's say I'd like to grab "green" from myobj by "F34"? (myobj could be any number of objects).

Can it be done by an AngularJS way or I have to take a look into SO question

Community
  • 1
  • 1
Haradzieniec
  • 9,086
  • 31
  • 117
  • 212

1 Answers1

2

If you're planning on using this scenario in multiple controllers / services I'd create a custom filter to do the work for me.

angular.module('myApp').filter('getColour', getColour);

function getColour() {
    return filter;

    function filter(object, key) {
        var colour;
        angular.forEach(object, function(set) {
            if (set.key === key)
                colour = set.color;
        });

        return colour;
    }
}

This can then be used like this:

$scope.colour = $filter('getColour')(myobj, 'F34');

Example fiddle

Ankh
  • 5,478
  • 3
  • 36
  • 40