0

I have some data that I would like to loop through with ngRepeat and access data dynamically that's either on the top level or nested under a couple of levels.

However, it seems like I can get the top level properties to show up, but not when its nested.

JS:

var mapping = [
    {property:'a'}, // works
    {property:'b.c1'}, // doesn't work
    {property:'b.c2'}  // doesnt work
];

var arr = {
    a: 'text',
    b: {
        c1: 'text2',
        c2: 'text3'
    }
};

HTML:

<div ng-repeat="mappingItem in mapping">
    <p>{{arr[mappingItem.property]}}</p>
</div>
muudless
  • 7,422
  • 7
  • 39
  • 57

3 Answers3

1

You can use angular's $parse service to evaluate the expression against arr:

$scope.map = function(property) {
    return $parse(property)(arr);
};

<div ng-repeat="mappingItem in mapping">
    <p>{{map(mappingItem.property)}}</p>
</div>

http://plnkr.co/edit/tPYcyT4HhqaepJZl0kd8?p=preview

noj
  • 6,740
  • 1
  • 25
  • 30
0

I doubt your approach will work. Reason being the way you are trying to access the object is incorrect, i.e.: arr[mappingItem.property] will become arr['b.c1'] but your object doesn't have a key 'b.c1'. @DivyaMV's suggestion won't work either because property b in the mapping isn't an object hence it doesn't have a key c1. I'd suggest you either change the structure of your object OR you change how you are trying to access your object i.e. use ng-if to check for multiple levels, OR instead of looping, display the properties one by one

Sylvan D Ash
  • 1,047
  • 13
  • 24
0

If you use {"property":"b","chiled":"c1"} type of structure then it works.

var mapping = [
    {property:'a'}, 
    {"property":"b","chiled":"c1"},// works
    {property:'b.c2'}  
];


 <div ng-repeat="mappingItem in mapping">
    <p>{{arr[mappingItem.property][mappingItem.chiled]}}</p> <!-- it works for second object-->
 </div>

Keval Bhatt
  • 6,224
  • 2
  • 24
  • 40
  • Won't this return `undefined` for first object? – Sylvan D Ash Jun 02 '15 at 12:17
  • yes i actually given example for nested json iteration so only second object work its just an simple example to iteration nested json so its on you to decided how i construct your json – Keval Bhatt Jun 02 '15 at 12:40