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

Leveraging the power of React Native with embedded RapidAPI functionality in the source

I had previously used the following code to retrieve a JSON file containing personal data in my React Native source code: async componentDidMount() { try { const response = await fetch('mydomain.org/personaldata.json'); const responseJson ...

Is there a way for me to access the data stored in session storage in Next.js?

One of the components in my project is a slider, which allows users to set the number of columns in an Image Gallery component. This code snippet shows the implementation of the slider component: export default function Slider({ value, handleChange }: ISl ...

Utilize React.useImperativeHandle() for declaring custom types

function App(){ const refEl:React.MutableRefObject<any> = React.useRef(null); // I am uncertain about the appropriate type here. React.useEffect(()=>{ if(refEl.current){ refEl.current.start() } }, []); return <Countdown ref={refEl} ...

What is the most efficient way to use jQuery to retrieve the count of tags associated with a variable

I am trying to filter my data retrieved from ajax using a function. Here is the initial code: var csvf = data.filter(function (el) { return ['TRUCK_CPX'].indexOf(el.TAG) >= 0 && ['CA5533'].indexOf(el.Chave) >= 0 }); Now ...

Encountering the following error message: "Received error: `../node_modules/electron/index.js:1:0 Module not found: Can't resolve 'fs'` while integrating next.js with electron template."

I am utilizing the electron template with next.js, and I am trying to import ipcRenderer in my pages/index.tsx file. Below is the crucial code snippet: ... import { ipcRenderer } from 'electron'; function Home() { useEffect(() => { ip ...

Merge data from api into visual charts using Google Chart Library

I received an API response with the following data structure: { "status": 200, "message": "OK", "data": [ { "_id": { "report_type": "robbery" }, "report_type": "robbery", "Counts": 11 }, { "_id": { "repo ...

Create a JavaScript code snippet that replaces the innerHTML of the function document.getElementById with

In my limited knowledge of JavaScript, I have come across an issue with the following code: function example() { document.getElementById("example").innerHTML = "<script>document.write(example)</script>"; } Unfortunately, this code doesn&ap ...

Using React: implementing a spinner upon clicking a button and transitioning to a new screen when the animation finishes

I have noticed that there are existing answers on incorporating spinners during fetch requests completion. However, my query pertains to stopping the animation once it reaches completion after a timeout. Additionally, I am seeking advice on best practices ...

Using Vue and vue-multiselect to create interactive options based on the selected language

I'm currently developing a Vue website with multilingual support. The chosen language is stored in a Vuex store and accessed through the computed property lang, like so: lang(){ return this.$store.state.lang } I use this lang property in v-if cond ...

Unable to execute node in vscode terminal

Can anyone help me figure out why I'm unable to run Node in my vscode terminal? I'm a newbie and currently using POP OS 22.04. https://i.stack.imgur.com/WqHWM.pnghttps://i.stack.imgur.com/GEHeA.png Your assistance would be greatly appreciated. ...

Troubleshooting the Gutter Problem in jQuery Isotope and Masonry

Currently, I am utilizing the Isotope jQuery plugin. While it is a fantastic tool, I am encountering a minor issue with aligning items in masonry mode. The width of my container is 960px, and I aim to have 4 items perfectly aligned as if they were adhering ...

Navigating to a particular div using a click event

I am trying to achieve a scrolling effect on my webpage by clicking a button that will target a specific div with the class "second". Currently, I have implemented this functionality using jQuery but I am curious about how to accomplish the same task using ...

What is the importance of having Express in the frontend?

As someone who is relatively new to the world of JavaScript and web applications, I recently came across an Express web application project that contained a public directory, client directory, and server directory. This has raised some questions for me. I ...

What is the best way to set the typing of a parent class to the child constructor?

I am seeking a method to inherit the parameter types of a parent's constructor into the child's constructor. For example: class B extends A { constructor (input) { super(input); } } I attempted the following: class B extends ...

Sending files using AJAX without FormData in Internet Explorer 9

Unfortunately, IE9 does not support FormData, making file uploads via XMLHttpRequest a more challenging task. Is there a workaround for this issue? I've come across mentions of using iFrames, but the process seems complex and unclear on how to transf ...

Laravel - Error in Symfony\Component\HttpFoundation\JsonResponse Argument 2

How can I retrieve the data in $users as an array and the data in $this->guard()->user() separately without it being inside an array? I attempted the following, but encountered an error - Argument 2 passed to Symfony\\Component\\H ...

Encountering an issue while attempting to extract an ACF field in WordPress using JavaScript

When I write the following code, everything works fine: <script> $(document).ready(function(){ var user_id = '<?php echo get_current_user_id(); ?>'; // This is working var subject = "<?php echo the_field('subject ...

Tips for saving the status of an accordion controlled by an angular directive

I am currently utilizing the accordion directive from angular-bootstrap. My goal is to save the is-open attribute of this accordion, so that when users navigate to another page on the website, the state of the accordion (i.e. is-open) remains unchanged. ...

Stripping out only the position attribute using jQuery

I have implemented a code with the following characteristics: The navigation items' texts are hidden behind certain Divs, which I refer to as Navigation Divs. When the mouse hovers over these pixels (navigation Divs), the text that is behind the ...

Modify the PrimeFaces dialog to be modal using client-side code

One of my primefaces dialogs is set up like this: <p:dialog widgetVar="dlg" width="320" height="220" modal="false" closable="false" showHeader="false" resizable="false" position="right,top"> I am looking to make this dialog modal if a certain eleme ...