Convert a nested array of objects to an array containing only objects

I have a unique challenge with an array of nested objects. How can I create a new array of objects by extracting values from nested properties? In cases where the onClick property is empty, I need to look for a children property and exclude the parent element from the new list. My goal is to iterate through the children array and retrieve the values. Please refer to the desired output provided below.

const headers = [{
    title: 'Arun',
    id: 'arunId',
    onClick: 'onClickArun'
  },
  {
    title: "George",
    id: 'georgeId',
    onClick: '',
    children: [{
        title: 'David',
        id: 'davidId',
        onClick: 'onClickDavid'
      },
      {
        title: 'Patrick',
        id: 'patrickId',
        onClick: 'onClickPatrick'
      }
    ]
  },
  {
    title: 'Mark',
    id: 'markId',
    onClick: 'onClickMark'
  }
];

console.log(headers.map(item => {
  return {
    title: item.title,
    onClick: item.onClick
  }
}))

Desired Output:

[{
    title: 'Arun',
    onClick: 'onClickArun'
  },
  {
    title: 'David',
    onClick: 'onClickDavid'
  },
  {
    title: 'Patrick',
    onClick: 'onClickPatrick'
  },
  {
    title: 'Mark',
    onClick: 'onClickMark'
  }
]

Any assistance would be highly valued.

Answer №1

To achieve this, you can utilize the Array#flatMap method along with a recursive callback.

const
    map = ({ title, onClick, children }) => onClick
        ? { title, onClick }
        : children.map(map);

var headers = [{ title: 'Arun', id: 'arunId', onClick: 'onClickArun' }, { title: "George", id: 'georgeId', onClick: '', children: [{ title: 'David', id: 'davidId', onClick: 'onClickDavid' }, { title: 'Patrick', id: 'patrickId', onClick: 'onClickPatrick' }] }, { title: 'Mark', id: 'markId', onClick: 'onClickMark' }],        
    result = headers.flatMap(map);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To achieve this functionality, you can utilize the Array.prototype.reduce method. In this case, you simply need to verify whether the parent's onClick property is empty and if the children property exists:

var headers = [{ title: 'Arun', id: 'arunId', onClick: 'onClickArun' }, { title: "George", id: 'georgeId', onClick: '', children: [{ title: 'David', id: 'davidId', onClick: 'onClickDavid' }, { title: 'Patrick', id: 'patrickId', onClick: 'onClickPatrick' }] }, { title: 'Mark', id: 'markId', onClick: 'onClickMark' }];


function getObject(headers, acc){
  return headers.reduce((acc, ele) => {
   if(!ele.onClick.length && ele.children){
      acc = getObject(ele.children, acc);
   }else{
      acc.push({"title": ele.title, "onClick": ele.onClick});
   }
   return acc;
  }, acc);
}
console.log(getObject(headers, []));

Answer №3

It appears that a depth-first search is the solution you need. By iterating through the array, you can recursively process each item with children and continue passing along the existing array. For items without children, simply add them to the list.

function retrieveChildren(array, result = []) {
  for (let item of array) {
    if (item.children) {
      retrieveChildren(item.children, result);
    } else {
      result.push({
        title: item.title,
        onClick: item.onClick
      });
    }
  }
  return result;
}

Answer №4

const headerElements = [{
  title: 'Arun',
  id: 'arunId',
  onClick: 'onClickArun'
},
{
  title: "George",
  id: 'georgeId',
  onClick: '',
  children: [{
    title: 'David',
    id: 'davidId',
    onClick: 'onClickDavid'
  },
  {
    title: 'Patrick',
    id: 'patrickId',
    onClick: 'onClickPatrick'
  }
  ]
},
{
  title: 'Mark',
  id: 'markId',
  onClick: 'onClickMark'
}
]
// Filtering out children with empty onClick
.map(item => item.onClick ? item : item.children)
// Creating flat array
const headers = [].concat.apply([], headerElements)
    .map(item => { 
        const temp = {};
        temp.title = item.title;
        temp.onClick = item.onClick;
        return temp; // Extracting onClick and title from each item
})


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

The onInvoke hook in Zone.js is receiving an inaccurate currentZone value

Greetings. In the comments for the ZoneSpec interface (found in zone.ts file), it states that the onInvoke hook must receive currentZone as the second parameter. If creating an interceptor zone, the reference to that zone should be passed as the second pa ...

Access exclusive content by subscribing now!

How can I return a reference to a subject from a service without allowing the receiver to call .next() on the subject? Let's say there is a service with a subject that triggers new events. class ExampleService { private exampleSubject = new Subjec ...

Retrieving POST data from requests in Node.js

My goal is to extract parameters from a POST request and store them in the variable postData using the request module. I found helpful information on handling post requests with Express.js here. Additionally, I came across this useful thread on how to retr ...

I am having difficulty accessing the environment variable stored in my Azure App Service configuration within my REACT application

After setting up my variable in the Azure app service configuration, I attempted to retrieve it from my React project. However, I consistently encountered an 'undefined' value. Azure App Service Configuration Link: https://i.sstatic.net/NextN.p ...

Implementing automatic selection mode in Kendo MVC grid

Seeking to modify the SelectionMode of a Kendo MVC Grid, I aim to switch from single to multiple using Javascript or JQuery upon checkbox selection, and revert back when the checkbox is unchecked. Is this feasible? Additionally, I am successfully binding a ...

The JComboBox, filled with a string array using a for loop, isn't showing up on the

I'm having trouble populating my JComboBox with numbers 25 to 50. Here's what I've tried: -- Variable Declarations -- String[] values = new String[25]; JComboBox comboBox = new JComboBox(); -- Main Code -- for(int i=0; i==values.length; ...

Is there an Angular Profile service offering getter and setter properties?

Can a singleton Angular service be created with getters and setters along with logic implementation? I was provided with the following code snippet and tasked with replicating it in an Angular service. Although it may seem straightforward, I'm finding ...

With a simple click of a button, I aim to have the ability to set a variable to true

I am looking to create a button that changes to true in the Script section. This will allow for a random number to be displayed in the paragraph element. <!doctype html> <html> <button id="button"> random number </button> ...

Obscured painting surface appearance using Three.js

I am attempting to incorporate a blurred texture into my Three.js scene, but the results are not what I expected. Canvas: var c = document.getElementById("myCanvas"); var context1 = c.getContext("2d"); context1.filter = "blur(16px)"; context1.beginPath( ...

A "Uncaught TypeError" error occurs when trying to execute a function using the dollar sign

After successfully recognizing the hover function, the console displays an error message: Uncaught TypeError: $ is not a function <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script> $(docume ...

Generating a dynamic form by utilizing a JavaScript JSON object

I need assistance with creating an html form based on a JSON object’s properties. How can I target multiple levels to generate different fields and also drill down deeper to access field details? I am open to suggestions for alternative formats as well. ...

Challenges with JSON Documents

const fs = require('fs'); const express = require('express'); const app = express(); app.use(express.json()); app.get('/submit', (req, res) => { let Com_Title = req.query.ComTitle; let Com_Text = req.query.ComTex ...

Send a parameter to a React hook

I am facing an issue with a Component that is using a separate hook. I am unable to pass any value to that hook, which is necessary for my use case. const onEdit = (index: number) => useMediaLinkImage(img => { setNodeImages(imgData => { ...

Having trouble with installing the most recent versions of React App dependencies

After cloning a project from GitHub, I attempted to install dependencies using npm install, but encountered an error: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email ...

Assigning a JavaScript code block to execute exclusively on designated pages

I have implemented webpack to bundle all my .js files into one app.js, which is utilized across all pages in my project. However, I have encountered an issue where code intended for one page is impacting another page where it is not required. For example, ...

"Discover the power of Algolia's docSearch feature

Currently, I am working on integrating Algolia DocSearch into my docusaurus project. After obtaining the api key and api id from Algolia, I am unsure of the next steps to take. I would appreciate guidance on the necessary procedures that need to be followe ...

What could be the reason for the unexpected "undefined" return value of this custom hook in

I've been working on creating a custom hook in React and here's the code I have so far: import {useEffect} from 'react'; const useFetch = (url) => { useEffect(() => { const fetchData = () => { const dat ...

I'm looking to leverage axios and useState-useEffect to collect data from numerous web pages. Any suggestions on how to do this efficiently

I stumbled upon a URL that leads to an API with a total of 42 pages and 826 data entries. The URL is . My goal is to store all the data in one variable for future filtering purposes, especially when implementing a "show more" button feature. Initially, on ...

How to locate every JavaScript event connected with an HTML element by utilizing Google Chrome

Looking for an easy method to identify all JavaScript events linked to a specific HTML element in Chrome? For example: HTML element <a href="#" class="cancel_link refresh_page">Cancel</a> Script: <script type="text/javascript"> $ ...

"Jquery with 3 buttons for toggling on and off individually, as well

There are 3 buttons available: button 1, button 2, and button 3. Button 1 toggles the show/hide functionality of the left side, button 2 does the same for the right side, and button 3 affects both sides simultaneously. What is the best approach to achieve ...