What is the best way to access and iterate through JSON data?

I am trying to extract data from my Json file, however, I cannot use a specific 'key' because it changes on a daily basis.

https://i.sstatic.net/sZySk.png

My attempted solution is as follows:

template: function(params) {
        const objects = JSON.parse(JSON.stringify(params.data.masterdetail));
        for (const obj of objects) {
          const keys = Object.keys(obj);
          const cont = 0;
          keys.forEach(key => {
            const valor = obj[key];
            console.log('value ', valor[0]); 
          });
        }

Initially, I tried using index 0 and then introduced 'cont', but with 0

console.log (value is undefined)....

If I instead use

console.log ('value' , valor['name'])
IT WORKS! But I cannot rely on specific keys, and if I use valor[0] it returns as undefined...........

Here is an example of the Json structure:

{
 "headers": [ 
   "headerName": "asdasd",
 ],   //end headers

  "datas": [
  "idaam": "11",
  "idorigen": "11",

   "masterdetail": [{
        "child1": {
          "name": "I AM",
          "age": "1"

        },

        "child2": {
          "name": "YOU ARE",
          "age": "2"
        },

        "child3": {
        "name": "HE IS",
        "age": "3"
        },
    }] //end masterdetail
  ]//end datas
}//end JSON

Edit :

I am unable to rely on 'keys' since the data fields may change from "name", "typeval" today to "surname", "id" tomorrow.

In the image you can see "4" bits of data.

1º obj[key]{
name = "adopt",
typeval= "",
etc
}
2º obj[key]{
"link" = "enlace",
"map" = "map"
etc
}

If I try this code: I can obtain "name" correctly but

It is NOT ALLOWED to use value['name'] or value[typeval] since the Json structure is always dynamic.

var objects = params.data.masterdetail[0];
        const keys = Object.keys(objects);
        let value;

        keys.forEach(key => {
          value = objects[key];
          console.log(value['name']);
          console.log(value['typeval']);
        });

What I need, for example, is:

 var objects = params.data.masterdetail[0];
        const keys = Object.keys(objects);
        cont = 0 ;

        keys.forEach(key => {
          value = objects[key];
          console.log(value[0]);
        });

However, value[0] leads to undefined results which complicates tracking 'link' in the 2nd object when the index might be different, like 4...

Apologies for any language barriers...

Answer №1

If you want to simply display the objects contained within the initial entry of the masterdetail array, you can use the following code snippet:

var items = params.datas.masterdetail[0];
const keysList = Object.keys(items);
keysList.forEach(key => {
  console.log('value ', items[key]); 
});

With a corrected version of the JSON data provided above, the resulting console output will be as follows:

value  {name: "I AM", age: "1"}
value  {name: "YOU ARE", age: "2"}
value  {name: "HE IS", age: "3"}

The question is slightly ambiguous regarding the desired output, but based on the code, this appears to be the intended result.

A couple of main errors in your approach were:

1) The masterdetail is an array, with all information stored in the first element. Therefore, you need to access that specific element to retrieve the objects within it. If there are multiple elements in the array, you would need another loop to iterate through them.

2) When iterating through an object's keys, there is no need for a separate iteration method for its properties. Your implementation included two loops serving the same purpose.

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

What is the most effective method to prevent the auto-complete drop-down from repeating the same value multiple times?

My search form utilizes AJAX to query the database for similar results as the user types, displaying them in a datalist. However, I encountered an issue where it would keep appending matches that had already been found. For example: User types: "d" Datali ...

The Stepper StepIconComponent prop in MUI is experiencing issues when trying to render styles from the styles object, leading to crashes in the app

Struggling to find a way to apply the styles for the stepper component without using inline styles. I attempted to replicate Material UI's demo, but encountered an error. The code from Material UI's demo that I want to mimic is shown below: http ...

Updating a specific field in a document using Node.js and MongoDB

Hey, I'm a beginner in nodeJS and I could use some help. I've been able to update an entire document easily but I'm struggling to update just a single value. Here's my code: router.patch("/:id", async (req, res) => { console.log(re ...

What is the best way to transfer information between different pages in an HTML document?

I am facing a specific requirement where I must transfer form data from one HTML page to another HTML page. The process involves a total of 5 pages, with the user entering data in the following order: 1st page: Name 2nd page: Weight 3rd page: Height 4t ...

PHP and Bootstrap combine in this dynamic carousel featuring thumbnail navigation

Looking to create a dynamic bootstrap carousel with image thumbnails at the bottom? After exploring various code snippets and solutions, I stumbled upon this link. While the code worked, I found the thumbnails to be too small. Below are the functions I use ...

Developing a REST API for a component with 18 interconnected elements

Currently, I am developing a REST API to expose a table to an Angular frontend, and I've encountered a unique challenge: The data required for display is spread across 10 different tables besides the main entity (referred to as "Ticket"). Retrieving t ...

What could be causing the issue with my dependency injection in my Angular application?

Let's get started angular.module('app', [ 'ngCookies', 'ngResource', 'ngSanitize', 'ngRoute' ]) This is my simple factory. Nothing fancy here angular.module('app') .factory(&apos ...

Utilizing a dynamic value in an Angular directive

For my latest project, I am working on developing a basic JSON pretty-printer directive using angular.js. Here is the code snippet I have so far: (function(_name) { function prettyJson() { return { restrict: 'E', ...

Issue with ESLint: Unexpected token found in JavaScript when converting to a dictionary

I've implemented a JavaScript code snippet that loops through an array of fields to find specific properties and then adds them to a dictionary. For another example, you can check out this site. return this.getFields() .reduce((mappings, field) =& ...

AngularJS special feature: enhance controllers and views by adding notification capabilities

What is the most efficient method for integrating common notification features into necessary controllers in AngularJS? The objective is to establish local notifications that can be effortlessly included or removed from any controller. Key factors includ ...

Error: Uncaught TypeError - Unable to change value of 'innerHTML' for null object in VueJs

I have been encountering a similar problem to others, but despite trying the solutions provided in previous questions, I am unable to resolve it. In my <template>: <modal name="MyModal" > <span class="myClass" id="visible">visible< ...

What is the best way to access the original observed node using MutationObserver when the subtree option is set to

Is there a way to access the original target node when using MutationObserver with options set to childList: true and subtree: true? According to the documentation on MDN, the target node changes to the mutated node during callbacks, but I want to always ...

The attribute "property" is not found in the specified type of "Request<ParamsDictionary>"

Struggling to enhance the Request interface in the express package with custom properties, I keep encountering this TypeScript error: TS2339: Property '' does not exist on type 'Request<ParamsDictionary>'. Any ideas on how to re ...

Running multiple web applications with different base directories on a single Express server

I am currently working on serving a website that requires different static directories for various routes. When a GET request is sent to the /tools* route, I want to utilize the /dist/toolsApp/ directory as the base directory for my frontend code. If ...

Retrieve characteristics from removed or replicated entities and allocate them to different entities

Looking for a bit of assistance with an array transformation: [ {Code:13938, Country:699, Name:"Crocs", codeProduct:1} {Code:13952, Country:699, Name:"Polo Club", codeProduct:14} {Code:13952, Country:699, Name:"Polo Club", codeProduct:1} {Code ...

Exploring the Debate: AJAX versus JSON for Cross Domain Built-in Security

I've noticed an interesting disparity in my ability to make cross-domain calls using AJAX. While I can successfully call the Twitter API with JSON in jQuery, I seem to be restricted from making similar calls outside of the current domain with regular ...

JQuery Mobile fails to apply consistent styling to user input check items within a list

I have successfully implemented the functionality to add user input items to a checklist. However, I am facing an issue where the newly added items are not adhering to Jquery Mobile's styling. Here is a screenshot showcasing the problem: Below is th ...

What is the best way to retrieve router parameters within a JSX component?

How can I pass the post ID as a prop to the EditPost component in order to edit it? render() { return ( <Router> <Switch > <Route path="/edit/:id"> <EditPost index={/*what do I do here?*/} /> ...

Is there a method to track the number of active onSnapshot listeners from Firestore in my application?

In my app, I am implementing a feature that dynamically removes query onSnapshot listeners and replaces them with new ones. To ensure that resources are properly freed up, I need to test the effectiveness of the unsubscribe function. Unfortunately, I do n ...

Duplicate text content from a mirrored textarea and save to clipboard

I came across some code snippets here that are perfect for a tool I'm currently developing. The codes help in copying the value of the previous textarea to the clipboard, but it doesn't work as expected when dealing with cloned textareas. Any sug ...