Parsing values from deeply nested objects and arrays

I've come across this issue before, but I'm having difficulty navigating through a nested structure. I can't seem to find any guidance in the right direction. Here is the object I'm attempting to parse:

const nestedArray = 
  { id       : 100
  , interval : 1000
  , enable   : true
  , topics: 
    [ { topic1: 
        [ { id: 0, 'error-code' : 100 } 
        , { id: 1, status       : 200 } 
        , { id: 2, mode         : 300 } 
      ] } 
    , { topic2: 
        [ { id: 0, count     : 100 } 
        , { id: 1, total     : 200 } 
        , { id: 2, operation : 300 } 
  ] } ] }

My goal is to loop through nestedArray, extract the topic name from topics (e.g., "topic1"), and retrieve the associated key-value properties within the nested array (e.g., "id" and "error-code").

I'm relatively new to this and have attempted methods like Object.entries, Object.keys, Object.values, and recursive functions. However, I haven't been able to get the desired values or encountered errors due to incompatible methods with the Object type. If someone could provide insight into how this can be accomplished, it would be greatly appreciated.

Answer №1

Is this what you had in mind?

const nestedArray = 
  { id       : 100
  , interval : 1000
  , enable   : true
  , topics: 
    [ { topic1: 
        [ { id: 0, 'error-code' : 100 } 
        , { id: 1, status       : 200 } 
        , { id: 2, mode         : 300 } 
      ] } 
    , { topic2: 
        [ { id: 0, count     : 100 } 
        , { id: 1, total     : 200 } 
        , { id: 2, operation : 300 } 
  ] } ] }

nestedArray.topics.forEach( topic =>
  {
  let key0 = Object.keys( topic)[0]
  topic[key0].forEach(el =>
    console.log( key0, '->', Object.keys(el). join(', ')))
  })

console.log( '\notherwise :')

nestedArray.topics.forEach( topic =>
  {
  let key0 = Object.keys( topic)[0]
  topic[key0].forEach(el =>
    console.log( key0, '->', Object.entries(el).map(([k,v])=>`${k}: ${v} `).join(', ')))
  })
.as-console-wrapper {max-height: 100%!important;top:0 }
.as-console-row::after { display:none !important; }

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

Error in calculation of $.post function in JQuery

I am facing an issue with my file delete.php, which contains the following code: <?php $folder = "./fak/"; $filename = $_POST['name']; unlink($folder.$filename); ?> Additionally, I have an index.html file with the below code: <html ...

Is it possible to host multiple React applications on a single port? Currently experiencing issues with running both an Admin panel and the Front side in production mode on the same Node.js API server

Is it possible to host multiple React applications on the same port? I am experiencing issues with running both an Admin panel and a Front side React app in production mode on the same Node.js API server. ...

Error: The requested resource does not have the 'Access-Control-Allow-Origin' header. The request is successful, but an error is being triggered

As I am trying to make an Ajax cross domain request, I have come across a strange issue. In the console of Chrome dev tools, I see the following error: "No 'Access-Control-Allow-Origin' header is present on the requested resource" Despite this ...

Navigating through the various iterations of jQuery

Unique Case Study I'm currently facing a dilemma involving the integration of jstree and jquery-ui datepicker. The scenario is this: I am attempting to utilize jquery-ui-datepicker on an input element that is dynamically inserted into the DOM after ...

You are limited to using a maximum of two custom tags within a custom div

I came up with this code that is supposed to style the elements differently based on their tag names. However, when I tested it, the styling did not work as expected. For example, 'London' should be displayed as a large and bold h1 text, while th ...

What is the best way to insert a new item into an array that is nested within an object?

Currently, I am delving into the world of using $resource in angularjs and finding great examples in this answer AngularJS $resource RESTful example. Fetching and creating records is working fine, but now my challenge lies in adding a "section" to an exist ...

Setting a default check on a checkbox within an ngFor loop in Angular 2

I'm attempting to initialize a default value as checked for a checkbox within my ngFor loop. Here is an array of checkbox items I am working with: tags = [{ name: 'Empathetic', checked: false }, { name: 'Smart money', che ...

Can you provide some guidance on accessing HTTP headers while using Promises to make AJAX requests?

Currently, I am working on resolving jQuery ajax requests using bluebird.js and I have found it quite challenging to access the HTTP headers of the request. Here is a snippet of the code I am working with: Promise.resolve($.get(...)).then(function(data){ ...

Having trouble configuring Travis; crashes just before installation begins

Today I attempted to set up Travis on my GitHub project but encountered a few roadblocks (refer to the screenshot). I experimented with different configurations in .travis.yml, such as the one below: language: node_js node_js: - "8.11.2" sudo: false b ...

Ways to guide user after logging out

My Angular front end includes the following code in app.js to handle user logout: .when('/logout', { templateUrl: 'mysite/views/logout.html', resolve: { authenticated: ['djangoAuth', function(djangoAuth){ return ...

Transmitting an email form using AJAX, Bootstrap, and Jquery

I am attempting to email a form using the code snippet below. This is a modified version of Bootstrap Validator created by 1000hz. $('#form').validator().on('submit', function (e) { if (e.isDefaultPrevented()) { alert("not workin ...

Adding information to an HTML table using JQuery

Is there a way to incorporate JSON data into an HTML table? The JSON data follows this format: https://i.stack.imgur.com/lzdZg.png This is the desired HTML table structure: <table class="table table-bordered table-hover "> ...

Tips for aligning the text of a typography element in Material-UI when its parent is fixed

Introduction to Home Component const HomeComponent = ({ mode, setMode }) => { return ( <Box m={-1} sx={{overflowX:'hidden'}}> <Navber/> <Stack direction="row" spacing={2} justifyContent="space-be ...

Add a checkbox element to a web API using ReactJS

I'm currently learning react and encountering an issue with checkboxes that I can't seem to resolve. I am working on a modal for updating and inserting data in a .net core web api, which is functioning correctly. However, within the app, I'm ...

The React component is failing to display updated data from the Redux store

I've been working with React and Redux, trying to update my counter value in the React view. I can successfully log the latest state of my Redux store, but the changes are not reflecting in my React view. const counter = (state = 0, action) => { ...

Using words instead of symbols to represent logical operators

When coding in C++, I typically prefer using the 'word' operators: not instead of ! and instead of && or instead of || I find it easier to read, especially when negating statements with not. Is there a similar approach possible in ...

A guide on incorporating a method using ES6 Rest into a JavaScript object

My goal is to enhance my Person constructor by adding a method that allows users to add friends. I wanted to utilize the "rest" feature of ES6 to pass a variable number of friends, but I seem to be stuck. My initial attempt resulted in an error ("Uncaught ...

Encountering an issue in Angular 8 where a class is not being added after the page loads, resulting in an

Looking to dynamically add a class to a div element using Angular? I have a condition isTrue, and am utilizing the angular function ngAfterViewInit() to add the class hideOnLoad after the page loads when isTrue becomes true. Instead of traditional javascri ...

Preventing Bull Queue from automatically re-starting jobs upon server restart

Currently, I am utilizing the bull queue system for processing jobs. Imagine a scenario where a job is in progress with an active status and I restart my development server. Upon restarting the worker script, the job remains in the active state within the ...

Utilize the effectiveness of the Ajax Success Handler for retrieving a distinct JSON entity

One of the features I am currently using involves an Ajax command that enables me to query data from a local server. In order to ensure smooth execution, it is crucial for me to return a JSON object through the success handler. The specific structure of m ...