Searching for a specific element within a JSON object by iterating through it with JavaScript

Here is the JSON file I am working with:

{
  "src": "Dvc",
   "rte": {
    "src": "dvc"
},
"msgTyp": "dvc.act",
"srcTyp": "dvc.act",
"cntxt": "",
"obj": {
"clbcks": [
  {
    "type": "",
    "title": "",
    "fields": [
      {
        "src": "label.PNG",
        "id": "Label",
      },
      {
        "id": "MSG",
        "text": "APPROVED",
        "type": "label"
      },
      {
        "id": "amt",
        "text": {
          "text": "{0:currency}",
          "substitute": {
            "data": [
              "$requestedAmount"
            ]
          }
        },
        "type": "lbl"
      },
   ],
  }
]

I am attempting to access the $requestedAmount value. This is the code snippet I have written so far:

In order to search for the existence of "data" in the JSON, I tried using a loop. Here's how my code looks like:

var order = obj.clbcks;
for ( i in order ) 
{
    if ( order[i].hasOwnProperty( 'data' ) )
      {
          //do something                         
      }
 }

However, I am encountering an error while running this code. Any assistance would be greatly appreciated. Thank you.

Answer №1

Initially, the JSON provided is invalid due to a missing final bracket and incorrect indentation.

{
  "src": "Dvc",
   "rte": {
    "src": "dvc"
  },

  "msgTyp": "dvc.act",
  "srcTyp": "dvc.act",
  "cntxt": "",
  "obj": {
  "clbcks": [
    {
      "type": "",
      "title": "",
      "fields": [
        {
          "src": "label.PNG",
          "id": "Label",
        },
        {
          "id": "MSG",
          "text": "APPROVED",
          "type": "label"
        },
        {
          "id": "amt",
          "text": {
            "text": "{0:currency}",
            "substitute": {
              "data": [
                "$requestedAmount"
              ]
            }
          },
          "type": "lbl"
        },
     ],
    }
  ]
}

Additionally, there is an issue with the loop - instead of looping through clbcks, it should be looping through clbcks.fields:

var order = obj.clbcks.fields;

Furthermore, shortening callbacks to clbcks may lead to confusion and disorganization.

Answer №2

Here's a suggestion:

var jsonData = {
"source": "Dvc",
"route": {
"source": "dvc"
},
"messageType": "dvc.act",
"sourceType": "dvc.act",
"context": "",
"object": {
"callbacks": [{
"type": "",
"title": "",
"fields": [{
"source": "label.PNG",
"id": "Label"
},
{
"id": "MSG",
"text": "APPROVED",
"type": "label"
},
{
"id": "amt",
"text": {
"text": "{0:currency}",
"substitute": {
"data": [
"$requestedAmount"
]
}
},
"type": "lbl"
}
]
}]
}
};

var amountObject = jsonData.object.callbacks[0].fields.find((obj) => obj.id === 'amt');

console.log(amountObject.text.substitute.data[0]);

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

Exploring data retrieval from nested arrays of objects in TypeScript/Angular

I have an API that returns an object array like the example below. How can I access the nested array of objects within the JSON data to find the role with roleid = 2 when EmpId is 102 using TypeScript? 0- { EmpId: 101, EmpName:'abc' Role : ...

Firebase Database: Unidentified node kind with separate Firebase initialization process

In order to replicate this issue, a minimal repository can be found at: https://github.com/ljrahn/firebase-unknown-node-type The problem arises when the firebase initialization logic is separated into a distinct package and then imported. This leads to an ...

Behat automates the process of populating form fields that are dynamically displayed as 'visible'

I'm facing an issue with a form that has hidden fields. When a user selects a checkbox, some of the hidden form fields are supposed to be revealed using the jQuery function slideToggle(). The code itself is pretty simple and you can see an example her ...

Increase in textbox size depending on selected dropdown value

Our concept involves offering three choices: Email #1 pulled from the database Email #2 retrieved from the database Input a new email Should the user select option #3, a textbox will expand at the bottom of the dropdown menu for easy entry of a new emai ...

Tips for managing JSON data in Node.js

I'm currently developing a bot to fetch the price of the Argentine peso using an API. However, I am encountering some challenges in retrieving only the sell price. if (command == "peso") { request('https://www.dolarsi.com/api/api.ph ...

Is it possible to swap out the content within a <div> element with an external piece of HTML code using JQuery or JavaScript whenever the viewport dimensions are adjusted?

<html> <head> </head> function () { var viewportWidth = $(window).width(); if (viewportWidth < 700) { $('#wrapper').load('A.html'); }; <body> &l ...

Error encountered with Angular JS Express JS File Upload: "undefined is not a function"

There seems to be an error displaying in the console: TypeError: undefined is not a function at C:\nodefiles\new\server.js:101:16 at Layer.handle [as handle_request] (C:\nodefiles\new\node_modules\express\li ...

Capturing attention within react-bootstrap drop-downs and pop-ups

Currently, I'm focused on enhancing accessibility features and I have a specific goal in mind: to confine the focus within a popover/dropdown whenever it is opened. Working with react-bootstrap, my inquiry revolves around finding out if there's ...

Challenge with the Table Filtering feature in a React application

Having an issue with the filtering functionality in React and MUI. The problem arises when adding a row first and then attempting to filter - the filter stops working. However, if I filter immediately without adding a row, it works as expected. To reprodu ...

What is the best way to measure the timing of consecutive events within a web browser, utilizing JavaScript within an HTML script tag?

Currently delving into the realm of JavaScript, transitioning from a Java/Clojure background, I am attempting to implement a basic thread-sleep feature that will display lines of text on the screen at one second intervals. Initially, I considered using t ...

The discrepancy in the array leads to a result of either 1 or an undetermined

Array x = [3,5,7,9,1] Array y = [3,7,8] z = x - y this should result in z = [5,9,1] (7 is common but I want it excluded) Below is the code snippet: function arrayDifference(x, y) { var arr = []; var difference = []; for (var i = 0; i<x.length& ...

Trading keys between arrays in JavaScript

I have a set of simple objects contained within an array: var myObject1 = [ {name: "value1", adddress: "545454545445"}, {name: "value2", adddress: "323233223"}, {name: "value3", adddress: "332 ...

Troubleshooting cross-origin resource sharing problem with Express NodeJS server running on localhost

Utilizing the fetch web API to send a POST request from ReactJS to an Express NodeJS server running on localhost with different ports. Using Client Fetch API fetch("http://localhost:8081/test", { method: "post", mode:"no-cors", headers: { ...

Successful AJAX Post request functioning exclusively within the Web Console (Preview)

When a user clicks on an element on the website, I have a simple AJAX request to send the ID of that element. However, the script only works in the Web Console under the Network -> Preview section and this issue occurs across all browsers. Here is the ...

An issue encountered with react-router-dom and the useLocation() function

Seeking guidance from experienced developers! I recently started using react-router-dom and encountered an issue with the useLocation() hook in my application. The error message states: "useLocation() may be used only in the context of a <Router> ...

Compose an email without the need to access the website

Is there a way to send email reminders to users without having to load the website pages? In the reminder section, users can select a date for their reminder and an email will be automatically sent to them on that date without requiring them to access the ...

Endless [React Native] onFlatList onEndReached callback invoked

Attempting to create my debut app using ReactNative with Expo, I've hit a snag with FlatList. The components are making infinite calls even when I'm not at the end of the view. Another issue might be related; across multiple screens, the infinite ...

The Quivering Quandaries of Implementing Jquery Accordions

For a demonstration of the issue, please visit http://jsbin.com/omuqo. Upon opening a panel by clicking on the handle, there is a slight jitter in the panels below during the animation. In the provided demo, all panels should remain completely still as t ...

Looking to utilize AngularJS validation in place of the default browser validation?

I am working on a form that contains two ng-forms for input validation. I have encountered two issues with my forms. 1) I am trying to implement a minlength validation for the Company input, but my current approach doesn't seem to be working. How can ...

Issues encountered when incorporating personalized CSS into a Vuetify element

Working with the Vuetify selector input component, v-select, and wanting to customize its style led me to inspecting it in Chrome and copying down the necessary classes. For instance, to change the font size of the active value, I utilized: .v-select__sel ...