What is the best way to dynamically search and retrieve data from a JSON object in Angular?

I am facing a challenge with my Angular (v. 1.6.3) app where I have fetched a JSON object containing stock price data. The structure of the JSON object only allows querying using brackets, with each key being a string that may include spaces, parentheses, periods, and other characters.

{ "Time Series (Daily)":
    "2017-11-17":
      "4. close": "82.4000"
    "2017-11-18":
      "4. close": "79.2000"
}

In my controller, I have assigned this JSON object to a variable ($scope.stocks) and attempted to create a way to dynamically update the displayed data in my HTML:

$scope.thisStock = $scope.stocks["Time Series (Daily)"][$scope.currentDate]["4. close"];

The $scope.currentDate value changes based on user input from the form in the HTML (for instance, through sliding a widget to select the current date for displaying the closing price of the stock).

Below is the HTML code intended to dynamically show the closing stock price based on the selected date:

{{thisStock | currency}}

I have verified that $scope.currentDate provides the correct date string format and that statically querying $scope.stocks works as expected. However, the issue lies in making the dynamic display work as intended. Currently, it seems that $scope.currentDate is being interpreted as a string rather than a variable, resulting in an invalid query message.

I suspect that I might be approaching this problem incorrectly. Any guidance would be greatly appreciated!

Answer №1

Keep an eye out for any updates in the variable currentDate

Give this a shot

$watch('$scope.currentDate', function() {
  $scope.thisStock = $scope.stocks["Time Series (Daily)"][$scope.currentDate]["4. close"];
});

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

Enhanced MUI TextField component with active cursor and focused state

When using the MUI TextField component as a single input form, I encountered an issue where the component loads with focus but no visible cursor to begin typing. To start typing, the user must click into the input field or press the tab key, which then act ...

What is the best method for retrieving multiple json_encode PHP outputs through Ajax?

$errMsgUsername=""; $errMsgPassword=""; if ($_POST['username']==""){ $errMsgUsername="Username is null"; } if ($_POST['password']==""){ $errMsgPassword="Password is null"; } echo json_encode(['er ...

Tips for utilizing date objects instead of date 'strings' while still obtaining the desired outcome

Below is a schema that I am working with: var MySchema = new Schema ({ event: { full: String, date: String, name: String, } }); To illustrate, here are some examples of the values: event.date = '16/02/20 ...

Problem with roles assigned through reactions on Discord

I've been working on a discord bot reaction roles command and everything seems to be going smoothly, except for one issue that I'm facing. After booting up the bot and running the command to create the embed, everything works fine. However, when ...

What is the best way to dynamically alter HTML elements on my webpage?

I have a selection of radio buttons on my webpage: <form ...> <input type="radio" name="people" checked> Member <input type="radio" name="people"> Manager <input type="radio" name="people"> Supervisor <!-- Here is t ...

Using MeanJS to assign a Mongoose object reference to an array in Angular

Having an issue with MeanJS and using the $update function of the $resource service in Angular provided by MeanJS. Here is a basic outline of my problem: Mongoose schema: var mongoose = require('mongoose'), Schema = mongoose.Schema; var Lotion ...

"Enhance your website with Ajax code that enables automatic refreshing of a PHP file, keeping its values up-to-date

Before diving in, I want to make it clear that my understanding of ajax is limited. I'm currently working on a small application where I have a load.php file that echoes 3 variables: $loadout[0]; $loadout[1]; $loadout[2]; The PHP file is functioning p ...

I recently developed a T3 stack project and am currently attempting to configure a next JS middleware, however, I am encountering issues with it not triggering as expected

Having issues with my T3 stack app where the next js middleware is not triggering. I've placed a middelware.ts file in the root directory. middleware.ts // middleware.ts import { NextResponse } from "next/server"; import type { NextRequest ...

JavaScript Date Validation: Ensuring Proper Dates

I am working with a date string that is in the format of "DD-MM-YYYY" and have successfully validated it using this code: var dateFormat = /(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-\d{4}/ ; if(!startDate.match(dateFormat)){ alert("'Start Dat ...

Proper techniques for storing element count in Protractor

I am a beginner when it comes to using Protractor and I am not entirely satisfied with the code snippet below, even though it is functional. My goal is to store the count in a variable (named "nb_before") and use it later on. However, due to the promi ...

Tips for encapsulating an image generated using execCommand

<input type="button" onclick="document.execCommand('insertimage',null,'http://barwoncopiers.com/wp-content/uploads/2011/03/linkedin-icon-45x45.jpg');" value="Img"/> <br> <div contenteditable="true" class="editor" id="edit ...

Error alert: The function name used in the import statement is not defined

I've taken the initiative to organize my JavaScript functions into separate files based on their respective web pages (index, login, register, etc.), and then importing them all into a main JS file. This helps with code maintenance and readability, pr ...

Add a third-party library file to Visual Studio

I'm currently working in Visual Studios and attempting to utilize the library provided at . However, I am encountering difficulties when trying to import the library. I have added the file to the project and attempted to use it within the Book.js (Vi ...

Using jQuery, you can utilize the $.when() function with both a single deferred object and an

In my current jquery setup, I am working with two variables. trackFeatures - representing a single ajax request, and artistRequests - an array of ajax requests. I am looking for a way to create a condition that triggers when both trackFeatures and artist ...

Input with dictionary route

I'm a newcomer to Python and still getting the hang of data structures in this language. Currently, I am developing an automated JSON parser in Python that reads JSON messages into dictionaries using Ultra-JSON: jsonObjs = ujson.loads(data) When I ...

Can someone recommend a straightforward PHP class for parsing JSON (or JSONP)?

Having to work with an older version of PHP (5.1.6) without access to convenient functions like json_decode, I am seeking a solution that doesn't require server privileges for installing extensions. I am looking for a lightweight and trustworthy clas ...

Dealing with two form submissions using a single handleSubmit function in react-hook-form

I have a React app with two address forms on one page. Each form has its own save address function that stores the address in the database. There is a single submit button that submits both fields and redirects to the next page (The plus button in the circ ...

Issue: The module "node:util" could not be located while attempting to utilize the "sharp" tool

Upon adding sharp to my Node.js application and attempting to use it, I encountered the following error: /Users/username/Documents/GitHub/Synto-BE/node_modules/sharp/lib/constructor.js:1 Error: Cannot find module 'node:util' Require stack: - /Use ...

What could be causing the Multer error in my Express.js application when attempting to upload a file for the second time, even though the first time was successful?

Whenever I try to upload a single file, the code works flawlessly. However, if I attempt to upload another file, I encounter the following Multer error: Error code: 'LIMIT_UNEXPECTED_FILE', field: 'myFile', storageErrors: [] To succes ...

What is the best way to execute individual API requests for various sheets within the same spreadsheet?

I am currently working on integrating the Google Sheets API with Node.js. I need assistance with understanding the correct syntax for calling two separate sheets within one spreadsheet. After reaching out to chatgpt and gemini, I received conflicting answe ...