Storing information in an array based on a specific flag

Currently, I am developing an Angular application where I am dealing with a specific array that contains a flag named "checked". Based on the value of this flag, I need to perform certain manipulations. Here is a snippet of my sample data:

const data = [{
    "checked": true,
    "children": [{
        "checked": true,
        "data": {
          "name": "myName"
        },
        "parent": {
          "data": {
            "name": "myName2"
          },
          "parent": {
            "data": {
              "name": "myName3"
            }
          }
        }
      }, {
        "checked": true,
        "data": {
          "name": "myNamePart2"
        },
        "parent": {
          "data": {
            "name": "myName2"
          },
          "parent": {
            "data": {
              "name": "myName3"
            }
          }
        }
      }
    ]
  }, {
    "checked": false,
    "children": [{
        "checked": true,
        "data": {
          "name": "myName4"
        },
        "parent": {
          "data": {
            "name": "myName5"
          },
          "parent": {
            "data": {
              "name": "myName6"
            }
          }
        }
      }
    ]
  }, {

    "checked": true,
    "children": [{
        "checked": true,
        "data": {
          "name": "myName7"
        },
        "parent": {
          "data": {
            "name": "myName8"
          },
          "parent": {
            "data": {
              "name": "myName9"
            }
          }
        }
      }
    ]
  },
  {

    "checked": true,
     "data": {
          "name": "myName10"
        },
        "parent": {
          "data": {
            "name": "myName11"
          },
          "parent": {
            "data": {
              "name": "myName12"
            }
          }
        }
  },
  {

    "checked": false,
     "data": {
          "name": "myName13"
        },
        "parent": {
          "data": {
            "name": "myName14"
          },
          "parent": {
            "data": {
              "name": "myName15"
            }
          }
        }
  }
];

Within this array, if the "checked" flag is true for any index, I would like to check the "checked" flag for each child element. If the "checked" flag is true for any child, I want to extract the data from the parent's name to the child's name, separated by a "/". For the given data, the final array should look like this:

result = ["myName3/myName2/myName","myName3/myName2/myNamePart2","myName9/myName8/myName7","myName12/myName11/myName10"]

How can I achieve this?

Answer №1

Here is a concise recursive solution that I came up with for your particular issue:

const data = [{
    "checked": true,
    "children": [{
        "checked": true,
        "data": {
          "name": "myName"
        },
        "parent": {
          "data": {
            "name": "myName2"
          },
          "parent": {
            "data": {
              "name": "myName3"
            }
          }
        }
      }, {
        "checked": true,
        "data": {
          "name": "myNamePart2"
        },
        "parent": {
          "data": {
            "name": "myName2"
          },
          "parent": {
            "data": {
              "name": "myName3"
            }
          }
        }
      }
    ]
  },{
    "checked": false,
    "children": [{
        "checked": true,
        "data": {
          "name": "myName4"
        },
        "parent": {
          "data": {
            "name": "myName5"
          },
          "parent": {
            "data": {
              "name": "myName6"
            }
          }
        }
      }
    ]
  },{

    "checked": true,
    "children": [{
        "checked": true,
        "data": {
          "name": "myName7"
        },
        "parent": {
          "data": {
            "name": "myName8"
          },
          "parent": {
            "data": {
              "name": "myName9"
            }
          }
        }
      }
    ]
  },{

    "checked": true,
    "data": {
      "name": "myName10"
    },
    "parent": {
      "data": {
        "name": "myName11"
      },
      "parent": {
        "data": {
          "name": "myName12"
        }
      }
    }
  },{

    "checked": false,
    "data": {
      "name": "myName13"
    },
    "parent": {
      "data": {
        "name": "myName14"
      },
      "parent": {
        "data": {
          "name": "myName15"
        }
      }
    }
  }
];


const compute = data =>
  data
    .flatMap(x => x.checked && x.children)
    .concat(data)
    .filter(x => x && x.checked && x.data)
    .map(x => createPath(x))
    .map(x => x.join("/"));

const createPath = (node, currentPath = []) =>
  node.parent
    ? createPath(node.parent, [node.data.name, ...currentPath])
    : [node.data.name, ...currentPath];

console.log(compute(data));

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 proper syntax for Angular 2 form element attributes?

As I was browsing through this insightful article, I came across the following snippets: <input type="search" [formControl]="seachControl"> and <input type="text" formControlName="street"> This made me ponder on the correct syntax for ...

What is the best way to retrieve a value from async/await functions?

async function fetchNetworkStatus() { const network = await Network.getConnection(); setConnection(network.isConnected); console.log(connectionStatus); if (network.isConnected) { return true; } else { ...

JavaScript xPath is ineffective at providing a return value

Trying to work through an issue with xPath and I am new to this concept. Any guidance or assistance in JavaScript would be greatly appreciated. Here is the simple HTML document that I have: <!DOCTYPE html> <html> <head> < ...

Integrating Material-UI Dialog with Material-table in ReactJS: A Step-by-Step Guide

I have implemented the use of actions in my rows using Material-Table, but I am seeking a way for the action to open a dialog when clicked (Material-UI Dialogs). Is there a way to accomplish this within Material-Table? It seems like Material-UI just appen ...

Pug Template Not Displaying Emojis or Special Characters in Sendgrid Email Subject Line

There seems to be an issue with rendering emojis or special characters in the subject header of the pug file, although they work perfectly in the body. I have compiled both the body and subject header separately using pug. const compileHtmlFunction = pug.c ...

Automatically scroll the chat box to the bottom

I came across a solution on Stackoverflow, but unfortunately, I am having trouble getting it to work properly. ... <div class="panel-body"> <ul id="mtchat" class="chat"> </ul> </div> ... The issue lies in the JavaScript t ...

Ways to programmatically compare all elements between two separate arrays

Is there a way to create a process where the first loop iterates through the elements of one array, while another loop goes through a second array and compares each element in the first array with all elements in the second array? For example: //first loo ...

How can I import a node-js dependency into my webpack project when the package already comes with type definitions included?

Don't bother using the deprecated @types/chalk package because the chalk library already has type definitions included. But I keep encountering the error message TS2307: Cannot find module 'chalk'. https://i.sstatic.net/uDIJi.png The proje ...

PlaneGeometry at x=0 y=0 z=0 for three.js on a flat surface

Hi there! I have a code snippet that currently renders an image vertically, and I'm looking to modify it so that the PlaneGeometry is drawn horizontally instead. Rather than rotating it with mesh.rotation.x=THREE.Math.degToRad(-90);, I'd like it ...

An easy way to activate the save button automatically

Is there a way to automatically enable the save button when a user checks the checkbox and enters text in the input field? I'm not sure what steps are needed or if there is an alternative approach to achieve this. jQuery("input[type='text&apos ...

What is the process for assigning default values to dynamically generated form elements?

I have been working on building a single-page application (SPA) using JavaScript and jQuery. During the process, I encountered an issue with a dynamic form. The user is able to add specific fields as needed, but if they don't generate and utilize all ...

Incorporate my personalized icons into the button design of ionic 2 actionSheet

I'm struggling to figure out how to incorporate my personal icon into the actionSheet feature of ionic 2/3. presentActionSheet() { let actionSheet = this.actionSheetCtrl.create({ title: 'Mode', buttons: [ { ...

What is the best way to separate array elements that have commas and create a distinctive array?

I have an array that looks like this: $array = ['a', 'b,c,d', 'e', 'f,g']; Now, I want to split the items with commas and create a unique array like this: $array = ['a', 'b', 'c', &apos ...

Transform an SVG string into an image source

Is there a way to convert an incoming string ' ' into an img src attribute and then pass it as a prop to a child component? I attempted the following method, but it hasn't been successful. `let blob = new Blob([data.payload], {type: &apos ...

When the page initially loads, the block appears on top of the upper block and remains in place after the page is refreshed

Upon initial loading, the block appears on top of another block but remains fixed upon page refresh. The same issue occurs in the mobile version of the site and occasionally displays correctly. The website is built on WordPress and optimized using Page Spe ...

Tips for managing numerous Axios requests in JavaScript

I have a scenario where I need to send 3 axios calls simultaneously from the frontend to the backend using the axios.all function to modify a MONGO DB database. The challenge I am facing is ensuring that if one of the requests fails, none of the other requ ...

Error: Jest + Typescript does not recognize the "describe" function

When setting up Jest with ts-jest, I encountered the error "ReferenceError: describe is not defined" during runtime. Check out this minimal example for more information: https://github.com/PFight/jest-ts-describe-not-defined-problem I'm not sure what ...

Tests are not visible to jasmine-node

Currently, I am utilizing jasmine-node and running it with the following command: node.exe path/to/jasmine_node --verbose path/to/my_file.js Despite successfully invoking Jasmine-node and receiving an error for incorrect paths, it appears that no tests a ...

Updating the count property of an object using setState in React

I have an array of integers ranging from 0 to 6 as my input. My goal is to create an object that gives the count of each number in the array. edition = [6, 6, 6, 1, 1, 2]; const [groupedEdition, setGroupedEdition] = useState([{"0": 0, "1&quo ...

Dynamic form in Yii2 developed by wbraganca that displays or hides fields depending on the value of a radio button

I am currently using the wbraganca dynamic form in a popup modal. I need to display and validate fields based on the selection of a radio button. To achieve this, I am calling a JavaScript function in the onchange event. <?= $form->field($model, "[{ ...