0

I have a table which is going to display results sent from the server, however the results themselves have a dynamic shape. There is also another API which provides the shape / schema of the nesting. So my HTML looks something like this:

 <tr ng-repeat="result in results">
     <td ng-repeat="path in schema.paths">{{result[path]}}</td>
 </tr>

Of course, this does not work since path may be one item, or it may be many items expressed as a dotted string. That is, path could be nesting1 which would work, or it could be nesting1.nesting2.nesting3 which would not work. How can I accommodate this use case without using the $compile service in JavaScript?

2 Answers 2

1

If I understand this question correctly, I think there is a Lodash function that can help you here.

It's called get. Usage:

var object = { 'a': [{ 'b': { 'c': 3 } }] };

_.get(object, 'a[0].b.c');
// => 3

_.get(object, ['a', '0', 'b', 'c']);
// => 3

_.get(object, 'a.b.c', 'default');
// => 'default'

For your case it might look something like:

controller.js

import { get } from 'lodash-es';

...

// Your controller code...

...

    this.getResultAtPath = path => get(this.results, path);

template.html

<tr ng-repeat="result in results">
     <td ng-repeat="path in schema.paths">{{ getResultAtPath(path) }}</td>
</tr>

If you don't want to take on the dependency, I suggest you take a look at their implementation for get.

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

2 Comments

Great thank you, I rolled my one as a basic map walk along the lines of: function getNestedMapItem(path, data) { var pointer = data for(var i = 0; i < path.length; i++) { var item = path[i] pointer = pointer[item] } return pointer }
@mobiusinversion nice :)
0

As mentioned above, get function should work. Alternatively you could flatten your 'result'. For example if there is an object: {'a': {'b': 3}} then flattened it would look like so: {'a.b': 3}

There are lots of implementations posted here, for example: flatten nested object

Comments

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.