What is the best way to ensure uniform property access across all nested objects within an array?

Is there a way to extract all the values associated with the property code within nested arrays of objects, regardless of how deeply they are nested?

[
  {code: '1', children: [
    {code: '11'}, {code: '12'}
  ]},
  {code: '2', children: [
    {code: '21'}, {code: '22', children: [{code: '221'}]}
  ]},
]

The desired output should be : [1, 11, 12, 2, 21, 22, 221]

Answer №1

flatMap is a valuable tool in situations like this, and can be paired with a recursive function, destructuring function parameters using default values, and array rest syntax.

const flatten = arr => arr.flatMap(
  ({ code, children=[] }) => [code, ...flatten(children)])

const flatten = arr => arr.flatMap(
  ({ code, children=[] }) => [code, ...flatten(children)])


const arr = [
  { code: '1', children: [{ code: '11' }, { code: '12' }] },
  { code: '2', children: [{ code: '21' }, { code: '22', children: [{ code: '221' }] }],},
]

console.log(flatten(arr))


In case you didn't know, the structure you're working with is known as a tree, it would be beneficial to delve deeper into its concepts, especially exploring the various traversal methods such as dfs and bfs.

Answer №2

Exploring generator functions with examples of depth-first search (DFS) and breadth-first search (BFS)

const laziness = [{
    code: 'A',
    children: [{
      code: 'A1'
    }, {
      code: 'A2'
    }]
  },
  {
    code: 'B',
    children: [{
      code: 'B1'
    }, {
      code: 'B2',
      children: [{
        code: 'B21'
      }]
    }]
  },
]

console.log([...bfs(laziness)])
console.log([...dfs(laziness)])

// breadth-first search
function* bfs(items) {
  const queue = [...items]
  while (queue.length) {
    const item = queue.shift()
    yield + item.code
    if (item.children) {
      queue.push(...item.children)
    }
  }
}

// depth-first search
function* dfs(items) {
  for (const item of items) {
    yield + item.code
    if (item.children) {
      yield* dfs(item.children)
    }
  }
}

Answer №3

To efficiently accomplish this task, you can utilize recursion along with the flatMap method in JavaScript:

function extractCodes(data) {
    return data.flatMap((item) => {
        const children = item.children ? extractCodes(item.children) : [];
        return [+item.code, ...children];
    });
}

const sampleData = [
    { code: '001', children: [{ code: '0011' }, { code: '0012' }] },
    { code: '002', children: [{ code: '0021' }, { code: '0022', children: [{ code: '00221' }] }],},
];

function extractCodes(data) {
    return data.flatMap((item) => {
        const children = item.children ? extractCodes(item.children) : [];
        return [+item.code, ...children];
    });
}

console.log(extractCodes(sampleData));

Answer №4

To achieve the desired outcome, recursion can be implemented:

function extractCode (nestedArray, current = []){
 nestedArray.forEach((element)=>{
  if ('code' in element) current.push(element.code)
  const keys = Object.keys(element);
  keys.forEach(key => {
   if (Array.isArray(element[key]) extractCode(element[key], current);
 }
 return current;
}

extractCode([
 {code: '1', children: [{code: '11'}, {code: '12'}]},
 {code: '2', children: [{code: '21'}, {code: '22', children: [{code: '221'}]}]},
])

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

following the history.back() function call, the subsequent codes are executed

<?php $ok_register = 0; if($ok_register != 1) { ?> <javascript type="text/javascript"> alert("1"); history.back(); </javascript> <?php } ?> <javascript type="text/javas ...

The API for /api/campaign/dynamicid has been resolved but no response was sent, potentially causing delays in processing requests within Next.js

Encountering a problem with my Amazon SES code in Next.js. Unsure where the mistake lies, seeking assistance to resolve the error. Feel free to ask if you have any questions. sendmail.js This is where I encountered an issue in the sendmail.js file while ...

What is the process for converting an integer into an array of dates?

Assuming a scenario where a user sets up a challenge with days_challenge: 5 & committed: ["mon", "tue", "wed", "thu", "fri"], how can we generate an array of dates starting from date_started: "2016-04-20" until the last day of the challenge using a mod ...

Intelligent decision-making for tic-tac-toe moves using C programming

While I understand that there might be an abundance of tic-tac-toe questions, I am seeking help on why this specific section is not functioning as expected. The code works perfectly except for this part where the computer fails to make a move; instead, it ...

Unable to transform Symbol data into a string - Error when making a React AJAX delete call

I'm encountering an issue where I am getting a Cannot convert a Symbol value to a string error in the console. My tech stack includes React v15 and jQuery v3. https://i.stack.imgur.com/qMOQ8.png This is my React code snippet: var CommentList = Reac ...

Encountered a problem while trying to fetch over 1000 records from the server using $

When fetching records from a database using JSON in $.ajax and ASP.net, everything runs smoothly. However, if the number of records exceeds 1000, it crashes and displays a "500 (Internal Server Error)" message. Below is the jQuery code: $.ajax({ ...

Sending Rails form data to a JavaScript click event

I'm currently working on a user profile form with a "Submit" button that triggers some client-side validations before proceeding. In my code, I've set up an intercepting click event on the submit button to run the validations and then proceed wi ...

Loading images dynamically in ReactJS allows for a seamless and customized user experience

I've been trying to dynamically fetch images from my images folder based on data retrieved from the database. Despite searching through numerous resources, I'm still struggling to crack this issue. Check out my code snippet below: import sword fr ...

Transfer half of the elements from one array to a newly created array

I am attempting to divide an array in half using a loop and copy each half into separate arrays. One half will be assigned to A1 and the other half to A0 for use in a recursive algorithm. However, I'm encountering issues with the copying process. Here ...

Need a brief Pygame tutorial on creating animations?

I am completely clueless on how to utilize classes. My goal is to create an 18-frame animation that can be displayed anywhere on a 5x5 grid, and do this a total of 25 times. Any suggestions on how I could achieve this? Here's what I have attempted so ...

Developing a web application using Node.js and Angular that can send both 401 Unauthorized and 200 OK responses

Upon clicking the register button on my form, it appears that Angular is setting the URL to /profile (a protected route) before the node server can authorize the JWT and send the 200 OK response. I'm unsure of how to address this issue. Even when I h ...

An error has occurred with the Firefox Addon: the module `path` cannot be located within the resource://gre/modules/commonjs/http.js

Currently developing a Firefox add-on on Windows10 with node v5.8.0 and npm v3.5.3, using Firefox v.45.0 The issue arises from the following line of code: var path = require("path"); The error message reads: Message: Module `http` is not found at resou ...

Angular - Organized hierarchy drag-and-drop functionality

Currently, I am working on an Angular application where I aim to incorporate a nested drag and drop feature with the ability to sort items within their own list. You can find a helpful StackBlitz example demonstrating how to implement nested drag and drop ...

Guide to implementing a variable delay or sleep function in JQuery within a for loop

I've noticed that many people have asked similar questions, but none of the solutions provided seem to work in my specific case. My goal is to incorporate a delay within a for loop with varying time lengths. These time lengths are retrieved from an a ...

Clicking a button to reset a json file

I have a task management program and I would like to implement a feature that allows users to reset the tasks to a predefined set of JSON data within the JSON file by simply clicking a button. For instance, if the JSON file contains multiple tasks, clickin ...

Deleting multiple entries when provided with an array of IDs in sequelize.js

My goal is to delete all instances in an array of ids at once, for example [1,2,3,4]. I attempted to use bulkDelete in sequelize.js but encountered an error stating that bulkDelete is not a method. When I tried using the destroy method in sequelize, only ...

Browsing through extensive data collection

Is there a quick way in Python to search through a list containing approximately 5 million strings of either 128-bit or 256-bit length and identify any duplicates? I am able to convert the strings into numbers, but I'm not sure if that will significan ...

Determine the hexadecimal color value by combining two different colors along with a specified percentage/position

Can a color in the middle of a gradient be calculated? var initialColor = 'FF0000'; var finalColor = '00FF00'; // At 50% between the two colors, it would result in '808000' var middleColor = determineMiddleColor(initialColor ...

A Promise-based value returned by a Typescript decorator with universal methods

I am currently working on creating a method decorator that can be applied to both prototype and instance methods. Referenced from: Typescript decorators not working with arrow functions In the code provided below, the instanceMethod() is returning a Prom ...

I am getting NaN as the output from my function, but I am unsure of the reason behind

For pracitce, I have created this code to calculate the total amount spent on gas and food using arrays. However, I am encountering an issue where it is returning NaN. const gas = [20, 40, 100]; const food = [10, 40, 50]; function total(gas, food) { ...