Exploring Angular2: Understanding how to retrieve an object with an unknown key

I am trying to showcase a specific value from different objects within a template. The path of the desired value depends on the object being referenced.

For example:

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

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

In this scenario, I aim to access the value "READ ME" using expressions like obj.b.2 or obj['b']['2'] for the first object. However, since I don't always know the location of the "READ ME" value in different objects.

To pinpoint the location of the value to display, I provide my template with a configuration array containing the keys needed to access it. For instance:

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

How can I effectively display "READ ME" in my template using the specified list of keys?

Answer №1

To retrieve the value, utilize the reduce function. As functions cannot be defined within templates, the logic must be implemented in the component.

Template

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

Component

function reduceValue(object, property){
    return object ? object[property] : null;
}

Live Demo

Answer №2

Instead of directly binding to an array or object, try binding to a "getter" function.

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

In your controller:

fetchCorrectValue() {
   // Test objects and determine the correct value...
   return theDesiredValue;
}

You can use other logic in your controller to help decide what the correct value should be. For example, you might receive objects from a service and need to perform tests before setting the "theDesiredValue". You can accomplish this using a setter:

set theRightValue() {
  // Perform necessary logic...
  theDesiredValue = something else.
}

This approach allows you to bind to results from various data structures by inspecting them, setting up required values, and returning them through the getter.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

`Localhost JSON parsing works fine, but encounters issues on the server``

Although there are many questions about json, none of them seem to answer my specific question. I have a part of my Symfony2 controller that is sending me data. return $this->createResponse(array( 'result' => $users )); die ...

When clicking initially, the default input value in an Angular 2 form does not get set

I am currently learning angular2 as a beginner programmer. My goal is to create a form where, upon clicking on an employee, an editable form will appear with the employee's current data. However, I have encountered an issue where clicking on a user f ...

Is there a way to execute a PHP script using Ajax without needing any return values?

Currently, I am attempting to execute a php script with ajax without needing any output or echos. Is there a method to achieve this? Below is the approach I have taken: $('button')[1].click(function () { $.ajax({ met ...

Send a JavaScript object to an MVC controller using an HTTP POST request

I'm encountering an issue while attempting to send a JavaScript object containing a string and a jstring to an MVC controller. Despite my code looking correct, I am receiving a null value in the controller. Any assistance would be greatly appreciated. ...

Utilizing the options object within JavaScript functions: A step-by-step guide

My current task involves gathering input as an argument along with some objects. function display(parameter) { var text = parameter.text; var element = parameter.element; document.getElementById(element).innerHTML = text; } As part of this task, I a ...

Managing the back button in Nativescript-Angular to toggle visibility

Struggling to toggle the visibility of an element in response to the back button event. <ActionItem icon="~/images/menu_3_dots.png" ios.position="right" android.position="right" *ngIf="isActionItemVisible"></ActionItem> construc ...

Why does the getter consistently generate the previous value?

Check out this code snippet: function User(fullName) { this.fullName = fullName; Object.defineProperties(this, { firstName: { get: function () { return fullName.split(" ")[0]; ...

An issue has arisen regarding the type definition for the random-string module

I am currently working on creating a .d.ts file for random-string. Here is the code I have so far: declare module "random-string" { export function randomString(opts?: Object): string; } When I try to import the module using: import randomString = ...

Discover the steps to implement user authentication with a combination of username, password, and token in an Angular 4

After developing a form using Angular 4, I encountered the need to send the form data via the post method with Angular 4. Testing with Postman showed that the data is being received correctly. To accomplish this, I must use Basic Auth with a username and p ...

Looping through a dropdown list to pass its items into an iframe

I need help passing dropdown list items to an iframe source (src) through a loop. The issue I'm facing is that the loop runs so fast that it directly goes to the last index of the dropdown list, causing the iframe to load only the last index item of t ...

The jQuery replacement should only be implemented on the new select box and not on the previous one

Let me illustrate the situation. I have a website and my aim is to gather information about the "Type of Business" for members on the site. I present all the current businesses that have been entered and allow users to choose one from the list. If a user w ...

`Can you provide instructions on modifying CSS using JavaScript once the window size reaches a specified threshold?`

Is there a way to use JavaScript to automatically adjust the font size when the screen reaches 1050px? ...

Is it a common issue for links to not work on the first click after ajax loads the page?

I've implemented a search box drop-down menu, and everything seems to be working well. However, I've noticed that the links are not functioning properly on the first click. I have to click somewhere else on the body before I can click on the link ...

Navigating through a HTML email Listserv with a click event scrolling feature

I am looking to create an interactive HTML email with a link that can scroll the recipient's browser to a specific section within the email. I am considering using Javascript and jQuery for this functionality. Can someone guide me on how to implement ...

Building a Laravel PHP application that dynamically generates a custom JSON object fetched from the database and passes it from PHP to

I am faced with the task of generating a custom JSON object by organizing data retrieved from PHP in my Controller. I have full control over what information goes where and in what specific order. To accomplish this, it seems like I will need to go throug ...

AJAX issue: "Content-Type header is missing the multipart boundary parameter"

Currently, I am encountering an issue while attempting to transfer a file from localhost to a server. The error message displayed in my network console is as follows, with status code 500: "no multipart boundary param in Content-Type" To address this p ...

What is the best way to retrieve the JSON data from a POST request made through AJAX to a PHP file and save it in an array variable?

My ajax request sends JSON data to a PHP file named 'receive.php'. user_name , user_id, etc. are defined at the beginning of my script but can be changed to anything else. Below is the JavaScript code I am using: const data = { name: user_na ...

Specifying the type of "this" within the function body

After going through the typescript documentation, I came across an example that explains how to use type with this in a callback function. I am hoping someone can assist me in comprehending how this callback will operate. interface DB { filterUsers(fil ...

Can an identification be included in a label element?

My inquiry is as follows: <label for="gender" class="error">Choose</label> I am interested in dynamically adding an id attribute to the above line using jQuery or JavaScript, resulting in the following html: <label for="gender" class="err ...

Inject various JavaScript data into different div containers

The issue at hand is quite straightforward. Here is a sample for displaying a single variable in a div with the "container" ID: let first = 5; document.getElementById('container').innerHTML = first; <div id="container"></div> How ...