What is the best way to retrieve data from a nested array of objects?

After examining the "Array" image, how can I access all levels within this array?

I attempted to use a foreach loop, but it only allows me to reach the first object and not the second object containing strings.


for (var key in result)
{
   if (result.hasOwnProperty(key))
      {
        console.log(key, result[key]);

            for(var item in result[key])
              {
                console.log(item);
               }
        }
}

I also experimented with:

result[key[item]]

However, this returned undefined results.

I understand that accessing elements by their name is straightforward, but since names constantly change, the solution needs to be adaptable.

I have included a Demo in the comments section to observe its behavior.

Answer №1

RetrieveKeys(obj) gives back a collection of all the keys inside obj.

var obj = {
  a: 1,
  b: 2,
  m: 3,
  x: 4,
  y: 5,
  z: 6
}

// Take out all the keys and store in an array:
var keys = RetrieveKeys(obj)
console.log("keys: " + keys);

// Loop through the object using its keys:
for (var i = 0; i < keys.length; i++){
  console.log("key " + keys[i] + " has value " + obj[keys[i]]);
}

Adjustment based on your feedback

I understand that you are looking to apply this approach to objects with multiple layers. My suggestion is to encapsulate the previous technique in a function and invoke it recursively for nested objects:

var obj = {
  a: {foo:"bar",foof:"barf"},
  b: 2,
  m: 3,
  x: {baz:{really:{more:{objects: "yeah, there could be a lot"}}}},
  y: 5,
  z: 6
}

function getKeysDeep(obj,prefix){
  // Take out all the keys and store in an array:
  var keys = RetrieveKeys(obj)
  //console.log(prefix + "keys: " + keys);

  // Loop through the object by its keys:
  for (var i = 0; i < keys.length; i++){
    if (obj[keys[i]] !== null && typeof obj[keys[i]] === 'object') {
      console.log("key " + keys[i] + "'s value is an object");
      getKeysDeep(obj[keys[i]],prefix + keys[i] + ": ");
    } else {
      console.log(prefix + "key " + keys[i] + " has value " + obj[keys[i]]);
    }
  }
}

getKeysDeep(obj,"")

Answer №2

Success! The loop executed without any issues.

Object.keys(result).forEach(function (key) {
      console.log(result[key]);
      var temp = result[key];
      Object.keys(temp).forEach(function (key) {
         console.log(temp[key]);
         var tempTwo = temp[key];
          Object.keys(tempTwo).forEach(function (key) {
            console.log(tempTwo[key]);
            var tempThree = tempTwo[key];
          });
       });
    });

However, @nvioli provided a more precise answer.

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 the enhanced capabilities of FeathersJS by integrating express-babelify-middleware

Attempting to integrate express-babelify-middleware with FeathersJS, an error message appears in the browser console: The error reads: ReferenceError: main_run is not defined This indicates that babelify may not be functioning correctly or I might be u ...

Setting up a div as a canvas in Three.js: Step-by-step guide

Is there a way to adjust the JavaScript in this three.js canvas example so that the scene can be contained within a specific div element on a webpage? Here is the example: https://codepen.io/PedalsUp/pen/qBqvvzR I would like to use this as the background ...

Exploring the depths of asynchronous calls in AngularJS with nested functions

Currently, I'm tackling a small project with AngularJS and finding myself tangled in multiple asynchronous calls that are starting to become chaotic. I know there must be a more efficient way to handle these calls, but I'm unsure of the best appr ...

Having trouble with NPM Moment.js in React: Why is moment__WEBPACK_IMPORTED_MODULE_2__format not functioning properly?

scenario, After resolving my current issue using dateFns (date-fns.org), I am interested in integrating Momentjs into the project as well. The task at hand involves converting data to a string format within an app built with create-react-app. However, wh ...

Cleaning a string of word characters in Javascript: a step-by-step guide

I have been working on cleaning strings that were transformed from word text, but I am facing an issue with removing the special character '…' When I click on the "clean" button, the script currently removes all dots and only one special ...

Troubleshooting Routing Issues in a Next.js Website Tutorial

After going through the next.js tutorial at https://github.com/zeit/next-learn-demo.git, I encountered an issue starting from stage 3 "dynamic routing". Despite the tutorial indicating that dynamic routing should be working from stages 3 to 8, it wasn&apos ...

Creating a general function to accommodate two alike types

Is there a way to modify the addSuffix function to handle two different types and return them simultaneously? Here's an example: type First = { name: string, address: string, } type Second = { name: string ...

Receiving undefined from a file object in JavaScript results in a function error

Struggling with reading the content of a file and storing it into an array for processing. Here's my current approach: let theFile = document.getElementById("getFile"); let fileVal = theFile.files[0]; let dataFromFile = fileVal.getAsDataURL(); alert( ...

What is the best way to transfer an ID to a dropdown selection list?

Whenever a user chooses an option from a drop-down menu, an event needs to be triggered. I have a checkbox that retrieves an ID from the database; based on this ID, a user can be added or removed from the drop-down menu. var ajReq = new XMLHttpRequest(); ...

Ways to determine the name of the calling function in an AJAX or XMLHttpRequest request?

I am currently exploring ways to programmatically identify the function name responsible for triggering an Ajax call in JavaScript or jQuery within an existing codebase. As I delve into instrumenting a large existing codebase, I am seeking to pinpoint the ...

What is the best way to dynamically update or display unique CSS styles when a service is invoked or provides a response in AngularJS using JavaScript

Seeking to display a unique CSS style on my HTML FORM prior to invoking a service in my code and then reverting back after receiving the response. I have implemented the use of ng-class to dynamically add the class when the boolean activeload1 is set to tr ...

Modifying button appearance upon clicking using JavaScript

JavaScript: const buttons = document.getElementsByClassName("togglebtn"); for (let i = 0; i < buttons.length; i++) { buttons[i].onclick = function () { this.classList.toggle("active"); } } html: <md-butt ...

Guide to showcasing images dynamically within a table

I am currently working on a dynamic table that updates its data using a script. My goal is to also display corresponding images of the groups next to their names in the table. Whenever the group names change, I want the images to change as well. The funct ...

The placement of the React.js/Next.js Loader is incorrect on the page

While I was trying to display a Loader over everything during data fetching from my API, I encountered a situation where the Loader was not appearing at the expected top level but inside the page itself. Even though the HTML tree showed it at the top level ...

Understanding how to retrieve an array from a function in object-oriented PHP

Recently, I have delved into object-oriented PHP programming. My main goal now is to fetch data from a database using functions and unpack the array using fetch_array method. I am thinking of a nice loop to iterate through each item. How can I tackle thi ...

Having trouble sending HTTP requests in Angular 6

I am currently facing an issue in my Angular application while trying to send an HTTP POST request to a Spring RESTful API. Despite my attempts, I have not been able to succeed and I do not see any error response in the browser console. Below is a snippet ...

"Reposition all elements contained within a div that have a specific class

I'm completely new to Javascript and I've been trying to move all elements with a specific class inside a particular div. After doing some research, I found a solution that worked using IDs. However, when I tried to adapt it to work with classNam ...

Filtering an array using criteria: A step-by-step guide

Currently, I am developing a system for Role Based permissions that involves working with arrays. Here is an example of the array structure I have: let Roles = { [ { model: 'user', property: 'find', permission: 'allow' ...

Get your hands on the base64 image by triggering the save as popup and downloading

I am facing a challenge with downloading a base64 image onto the user's machine. So far, I have attempted the following steps: var url = base64Image.replace(/^data:image\/[^;]+/, 'data:application/octet-stream'); window.open(url); an ...

Send your information without having to navigate away from the current

This is my form <form id="reservationForm" action="sendmail.php" method="post"> ... . . . . <input type="image" src="images/res-button.png" alt="Submit" class="submit" width="251" height="51px"> Here is my javascript $("#reservationForm").su ...