Arranging and Filtering an Object Array Based on their Attributes

Here is an example of a JSON array called items:

var items = [
  {
    Id: "c1",
    config:{
      url:"/c1",
      content: "c1 content",
      parentId: "p1",
      parentUrl: "/p1",
      parentContent: "p1 content",
    }
  },
    {
    Id: "c2",
    config:{
      url:"/c2",
      content: "c2 content",
      parentId: "p1",
      parentUrl: "/p1",
      parentContent: "p1 content",
    }
  },
      {
    Id: "c3",
    config:{
      url:"/c3",
      content: "c3 content"
    }
  },
  ]

The desired output should look like this:

var items = [
  {
    Id: "p1",
    config:{
      url:"/p1",
      content: "p1 content"
    },children:[
      {
        Id: "c1",
        config:{
          url:"/c1",
          content: "c1 content"
          }
      },{
        Id: "c2",
        config:{
          url:"/c2",
          content: "c2 content"
          }
      },
       ]
  },
  {
    Id: "c3",
    config:{
      url:"/c3",
      content: "c3 content"
    }
  },
  ]

If an object has parent properties, they should be nested under the parent's children property. If you need help converting this structure, feel free to ask for assistance. Thank you.

Answer №1

This snippet of code has not been tested, but it may provide some assistance:

var fresh_items = [];

for(key in items) {
  var identity = items[key].config.parentId;
  if(identity) {
    if(!(prev_parent = retrieve_previous_parent(identity))) { 
      prev_parent = {ID: identity, config: {
        link: items[key].config.parentUrl,
        text: items[key].config.parentContent,
        //... Other parent attributes
      }, descendants: []};
    }
    prev_parent.descendants.push({/* Attributes for the child object */});

  }
}

function retrieve_previous_parent(identity) {
  for(n in fresh_items) {
    if(fresh_items[n].ID == identity) return fresh_items[n];
  }
  return false;
}

Answer №2

Here is the array that needs to be processed, with an additional item for p1:

var items = [{
    Id: "p1",
    config:{}
  },{
    Id: "c1",
    config:{
      url:"/c1",
      content: "c1 content",
      parentId: "p1",
      parentUrl: "/p1",
      parentContent: "p1 content",
    }
  },{
    Id: "c2",
    config:{
      url:"/c2",
      content: "c2 content",
      parentId: "p1",
      parentUrl: "/p1",
      parentContent: "p1 content",
    }
  },{
    Id: "c3",
    config:{
      url:"/c3",
      content: "c3 content"
    }
  },
];

Instructions for processing the array:

orphans = [];
parents = {};
items.forEach(function(item){
    parents[item.Id]=item;
});
items.forEach(function(item){
  var parent = parents[item.config.parentId];
  if (parent){
    parent.children = parent.children || [];
    parent.children.push(item);
  }else{
    orphans.push(item);
  }
});
console.log('Processed array:', orphans);

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

Combining an Image with a CanvasJS Graph and Generating a Downloadable Image of the Composite

I am attempting to combine an image (a background image for my graph) with my canvasJS chart. Once these elements have been merged on a canvas, I aim to obtain a DataURL of this canvas, enabling me to download an image of it (depicting the graph along wit ...

Determine which children should be displayed in a Kendo treeview based on the field titled "ParentId"

After converting a list of records into JSON format, I am looking to transform this data into a hierarchical KendoTreeView. Here is the JSON data: [ { "id": 1, "name": "A", "parentID": 0, "hasItems": "true" }, { "id": 2, "name": "B", "parentID": 1, "has ...

In my Angular application, I have two div elements that I want to toggle between. When a button located in the first div is clicked, I need

I am working on a code snippet that requires me to hide div1 and display div2 when the button in div1 is clicked using Angular HTML5. Currently, I have two separate modal pop up template files and JS controllers for each of them. Instead of having two po ...

Stopping Form Submission with MUI TextField

I am currently creating a form using React along with MUI. I'm trying to figure out how to prevent the form from being submitted when the user hits the enter key. Usually, I would use e.preventDefault(), but for some reason it's not working in th ...

Error: Unable to access property 'count.' because it is undefined

componentDidMount(props) { this.interval = setInterval(() => { if (props.count !== 0) { this.stateHandler() } }, 1000) } Encountering an issue with the interval, as the console is displaying the following error: Type ...

Are there any Java alternatives comparable to PHP arrays with non-numeric keys?

How can we convert this PHP array to Java? HashMap<String, String> user = new HashMap<>(); user.put("name", "John"); user.put("email", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="92f8fdfafcd2fff3fbfebcf1fdff" ...

Retrieve the red, green, and blue components of a color in the RGB format

When I retrieve "rgb(18, 115, 224)" from a DOM element, I need to convert this color to hexadecimal in order to assign it to a span element. To get the hexadecimal equivalent of the color, I can use the following code snippet: "#" + componentToHex(r) + co ...

Working with Three.js: Utilizing the SpotLight and dat.gui

I have implemented a SpotLight in my scene along with an OctahedronGeometry as a visual aid for the user. The SpotLight can be moved using transformControls by selecting it, which is working properly. However, the issue arises when I try to edit the setti ...

Once the Json content is loaded into the array, proceed to append

I am facing an issue with my ajax function that loads thumbnails. The function is being called by another ajax function, and the parameter is retrieved from there in the loop. I have attempted to wait for the ajax call to finish using .done and .ajaxCompl ...

Do not decode HTML content within an iframe; instead, extract the data directly from the HTML source

To expedite execution time, we have made the decision to not display the table in the iframe as it is invisible to the client. However, we still need to update the main page table by copying its contents. The approach we are taking is that the iframe shou ...

Expanding the content of a single page by clicking on a separate tab

I have a link on Page A. Page B has two tabs, with the content of tabs 1 and tab 2 currently set to "display:none". I want clicking the hyperlink on page A to automatically open or activate the second tab on page B. I am seeking a solution using JavaScri ...

Is it possible to dynamically populate a dependent select box using Jinja variables?

I am currently using Flask with Jinja2 templates, and I need assistance in creating dependent select boxes. How can I achieve this using Jinja2 or a combination of JavaScript and Jinja2 variables? For example: On the Python side: @app.route('/&apos ...

Tips for accessing the reference of a child when it is a functional component

Trying to implement a Higher Order Component (HOC) to access the ref of any component. It works perfectly fine when regular JSX is passed, but encounters issues when a functional component is passed: class GetRef extends React.Component { state = {}; ...

What is the process of transforming the content of a file into an array using JavaScript?

I have a file named "temperatures.txt" that contains the following text: 22, 21, 23 Is there a way to transfer the contents of this file into a JavaScript array? const weatherData = [22, 21, 23]; ...

Understanding the separation and communication techniques in Vue.js components

I recently developed a small vuejs application and I find myself getting confused with the functioning of components. Here is the code snippet that I have been working on: <div id="app"> <div v-if="loggedIn"> <nav> <r ...

At first, struggling to dynamically adjust the height of a collection view based on JSON data in a Swift project

Within a tableview cell, I am utilizing a collection view. When I return homeData?.result?.category_json?.count ?? 0 to populate the collection view with JSON data, the height of the collection view does not adjust dynamically at first. However, when I scr ...

Displaying client-side filtered rows in a jqGrid with postData filter upon initial loading

Our website includes a jqGrid that initially retrieves its rows using the built-in ajax fetch feature, returning a json object. We then apply filtering and searching on the client side by creating custom functions to generate postData filters. However, we ...

Tips for verifying the status of a solr server

In my E-commerce application, I have successfully implemented a search feature that connects to Solr running on port 8983 to retrieve search results. The Solr URL is: url = solrURL+"/solr/db/select/?qt=dismax&wt=json&&start="+start+"&rows ...

Disappearing act: The vanishing act of the Bootstrap 4 Smart Scroll Mobile

Utilizing the Smart Scroll feature from in Bootstrap has been successful on desktop, but issues arise on mobile devices. When scrolling down and returning to the top, the navbar experiences glitches by hiding again. Attempting solutions from Bootstrap 4 S ...

It seems that there is a null value being returned in the midst of the

I have developed a model using express. While setting this in one function, it returns null in another function, forcing me to use return. What is the proper method to handle this situation? const Seat = function(seat) { this.seat = seat.seat; this. ...