Explore an object to locate an element along with its parent

Here is an example of an object:


    $scope.categories = [
    {
        value: 'One',
        id: 1,
        childs: [
          {
            value: 'Two',
            id : 2,
            childs: [
              {
                value: 'Three',
                id: 3
              },
              {
                value: 'Four',
                id: 4           
              }
            ]
          },
          {
            value: 'Five',
            id: 5
          },
          {
            value: 'Six',
            id: 6,
            childs: [
              { 
                value: 'Seven',
                id: 7
              },
              {
                value: 'Eight',
                id: 8
              }
            ]        
          }
        ]
      },
      {
        value: 'Nine',
        id: 9
      }
    ];

If I know the id, how can I get the element and its parents?

I am using AngularJS but it doesn't seem to be helping me with this task...

Answer №1

To streamline your array, utilize the following function:

function flatArray(o, parent) {
  let result = []
  o.forEach(child => {
    child.parent = parent
    result.push(child)
    if (child.childs) {
      Array.prototype.push.apply(result, flatArray(child.childs, child.id))
    }
  })

  return result
}

How to use it:

let categories = [
    {
        value: 'One',
        id: 1,
        childs: [
          {
            value: 'Two',
            id : 2,
            childs: [ /* ... */ ]
          },
          /* ... */
        ]
    ];

let flattenedCategories= flatArray(categories)

Check out the results:

Flat Array[9]: [
  {
     value: 'One',
     id: 1,
     childs: [/*...*/],
     parent: undefined
  }, {
     value: 'Two',
     id: 2,
     childs: [/*...*/],
     parent: 1
  }, 
  ...
]

This method makes it easy to locate the correct ID and its parent.

Answer №2

Like Icycool mentioned before, the key is to search through your collection recursively. While it's recommended that you try to solve it on your own, here's a quick solution provided in the code snippet below:

function find(id, children) {
  for (let child of children) {
    if (child.id === id) {
      return [child.id];
    } else if (child.childs && child.childs.length) {
      const result = this.find(id, child.childs);
      if (result.length) {
        return [...result, child.id];
      }
    }
  }

  return [];
}

const categories = [
  {
    "value": "One",
    "id": 1,
    "childs": [
      {
        "value": "Two",
        "id": 2,
        "childs": [
          {
            "value": "Three",
            "id": 3
          },
          {
            "value": "Four",
            "id": 4
          }
        ]
      },
      {
        "value": "Five",
        "id": 5
      },
      {
        "value": "Six",
        "id": 6,
        "childs": [
          {
            "value": "Seven",
            "id": 7
          },
          {
            "value": "Eight",
            "id": 8
          }
        ]
      }
    ]
  },
  {
    "value": "Nine",
    "id": 9
  }
];

console.log(find(8, categories));

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

How can I detect Mongoose events through syntax?

Is there a way to detect the open event in Mongoose based on their documentation located here? According to the documentation, once connected, the open event is fired on the Connection instance. If you're using mongoose.connect, the Connection is m ...

Rotating an object in Three.js: Animate back and forth along two different azimuth angles

My three.js project features a 3D object that is meant to be viewed from the front only, as it appears as a single plane and is transparent from the back... Using orbitControls, I have restricted movement of both azimuth and polar angle... To enhance the ...

Creating a custom jQuery plugin for exporting data

I am crossing my fingers that this question doesn't get marked as 'already answered' because I have thoroughly searched previous questions and unfortunately, my specific case is not listed anywhere. I have successfully created a jQuery func ...

Conceal content upon clicking with JavaScript

Showing a form after clicking a link can be achieved using this code: $(function () { $('.msg').on('click', function (e) { e.preventDefault(); $(this).next('.msgarea').show(); }); }); <a href="" cl ...

"Patience is key when waiting for the alert dialog response in Vuetify

I currently have a reusable component called Alert.vue. <v-dialog v-if="alertDict" v-model="alertDict.showDialog" max-width="460"> <v-card> <v-card-title>Title</v-card-title> & ...

Encountering difficulty retrieving information in an Angular application on an iPad mini device

I am currently developing an angular application for a dashboard. The issue I am facing is related to making http requests from my controllers. Everything works perfectly when I build and run the project using grunt on my machine, fetching data from the ex ...

Execute index.js code from index.html using NodeJS and Express

Currently, I am diving into the world of NodeJS and Express using Replit.com for a small project. The main objective is to develop a basic input field that, upon submission, will post to different channels such as Discord and Twitter. The piece of code be ...

Navigate to a different subdomain and place a cookie on the newly redirected subdomain

The version of Express is 4.x NodeJS is running on version 12.x At a.example.com, I have a listener for the GET method that redirects to b.example.com and sets a cookie on b.example.com. app.get('/foo', (req, res) => { res.cookie(' ...

Tips for efficiently playing a WAV file in JavaScript by building an AudioBuffer

I'm having trouble playing the WAV file located at this link. The file plays fine in VLC and the details show that it is a Mono IMA WAV APDCM Audio (ms) file sampled at 24000Hz with 16 bits per sample. However, when I try to play the file by embeddin ...

What is the most effective way to loop through HTML elements using wildcards in Puppeteer to extract innerText?

Seeking insights for educational purposes, I am in search of the reviews on this specific page . Each page contains 10 reviews, and I have a set of HTML selectors (previously used code) to extract these comments: #review_593124597 > div:nth-child(1) &g ...

Probability of an event occurring when represented as whole numbers in percentage form

Currently, I'm developing a unique job system within a Discord bot that allows users to mine various types of ores. The probability of receiving specific ores is based on the user's mining skill level, which is stored in a database and can vary a ...

The order in which JavaScript is being executed is being reversed

function checkForDuplicate(center, email) { $.ajax({ type: "POST", url: "../staff/staffDA.php", data: "funId=-4&center=" + center + "&email=" + email, success: function (data) { if (data.split('| ...

The next.js Head component that is imported from next/head is not functioning correctly when used on share pages

I recently switched my website from create-react-app to create-next-app, but I'm having issues with the Head(app/head) component. Let's say I have a blog section with pages structured as follows: pages/blog/index.js and pages/blog/[slug].js. In ...

Creating a dynamic select input in React that displays a default value based on other user inputs

My dilemma involves working with two radio buttons, named radio1 and radio2, along with a select input. The options available in the select input are conditional based on the selected radio button. I am aiming to automatically set the value of the select t ...

What is the best way to pass a function along with its state to utilize useContext in React

Currently attempting to grasp the concept of using react hooks. I have implemented createContext and am looking to pass both state and a function to other components, but could use some guidance on how to achieve this. I'm also questioning if it is ev ...

Display only one field and hide the other field using a jQuery IF/ELSE statement

Hey there! I have a situation where I need to toggle between two fields - one is a text field and the other is a text_area field. When a user clicks on one field, the other should be hidden and vice versa. I've tried using JQuery for this: $(document ...

Retrieve content from JSON post data

I have been facing an issue where I am trying to send a JSON file from a web page to a nodeJS server. My goal is to assign the JSON file to an object on the server side and print it out in the console. Despite researching extensively online and attempting ...

What is the best way to handle parsing JSON using external middleware after the removal of body parser in Express?

Having trouble parsing JSON with external middleware after Express removed the body parser? I used to rely on Express bodyParser for handling JSON posts, but after updating Express, my JSON requests are returning null. It seems like I was using the wrong ...

Using Jquery to Connect a Change Event to Child Elements

<form id="duration"> <label for="change-chart-type-24H" > ; <input style="display:none;" name="chart-type" id="change-chart-type-24H" type="radio" value="24H">24H ...

Transformation of looks post a refresh

Initially, the CSS and appearance of the page look fine when I first open it (after clearing the cache). However, upon refreshing the page, a part of it changes (specifically, the padding direction of a div). This change occurs consistently with each refre ...