0

I want to display a specific value of different objects in a template. The path of the value to display depends of the object.

Here a example :

let obj = {
    "a": "a",
    "b": {
       "1": "1",
       "2": "READ ME"
    }
}

let obj2 = {
    "x": "x",
    "y": {
       "foo": "1",
       "bar": {
           "test": "READ ME"
       }
    }
}

In this example I want to read the value "READ ME" like this obj.b.2 or obj['b']['2'] for the first object. However I don't know where is the READ ME value depending on objects.

To know where is located the value to display, I pass to my tempate a config array with the list of the keys to call: like this :

config = ['b', '2'] // For the first object
config = ['y', 'bar', 'test'] // For the second object

How can I display "READ ME" in my template with my list of keys ?

2 Answers 2

2

You can use the reduce function to obtain the value. You cannot define functions in your template so the logic will have to live in the component.

Template

{{config.reduce(reduceValue, obj)}}

Component

public reduceValue(object, prop){
    return object ? object[prop] : null;
}

Demo

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

Comments

0

Bind to a "getter" instead of directly to an array or object.

<div>{{ getTheRightValue ( ) }}</div>

In your controller:

get theRightValue ( ) {
   // Test objects, determine correct value...
   return theCorrectValue;
}

Other logic in your controller can help determine what "theCorrectValue" is as well, say for instance you get back objects from a service, when they return, do your tests and set "theCorrectValue" to whatever you need. A setter can do this nicely:

set theRightValue ( ) {
  // do your logic, etc...
  theCorrectValue = etc. etc.
}

This way you can bind to results from completely different structures. You just inspect them, set up what you need, and have that returned from the getter.

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.