Most efficient method for nesting child objects within an array of objects using JavaScript

Hey experts, I'm on the hunt for the most efficient method to transform this data:

 [
  { "id": 1, "animal": "cat", "age": 6, "name": "loky" },
  { "id": 2, "animal": "cat", "age": 3, "name": "michu", "parent": 1 },
  { "id": 3, "animal": "cat", "age": 2, "name": "boots", "parent": 1 },
  { "id": 4, "animal": "dog", "age": 9, "name": "bones" },
  { "id": 5, "animal": "dog", "age": 6, "name": "chok", "parent": 4 },
  { "id": 6, "animal": "dog", "age": 6, "name"": "cofee","parent": 4 }
]

into the following format:

 [
  { "id": 1,
    "animal": "cat",
    "age": 6,
    "name": "loky",
    "childs":[ { "id": 2, "animal": "cat", "age": 3, "name": "michu", "parent": 1 },
               { "id": 3, "animal": "cat", "age": 2, "name": "boots", "parent": 1 }] 
  }
  ,
  { "id": 4,
    "animal": "dog",
    "age": 9,
    "name": "bones",
    "childs":[{ "id": 5, "animal": "dog", "age": 6, "name": "chok", "parent": 4 },
              { "id": 6, "animal": "dog", "age": 6, "name": "cofee", "parent": 4 }]
  }
 ]

Remember, utilize the "parent" key to nest under "childs". I managed to find a solution but it involved multiple functions, surely there's a more efficient way.

Thanks in advance and please pardon any language mistakes.

Answer №1

const pets = [
  { id: 1, type: 'cat', age: 6, name: 'loky' },
  { id: 2, type: 'cat', age: 3, name: 'michu', parent: 1 },
  { id: 3, type: 'cat', age: 2, name: 'boots', parent: 1 },
  { id: 4, type: 'dog', age: 9, name: 'bones' },
  { id: 5, type: 'dog', age: 6, name: 'chok', parent: 4 },
  { id: 6, type: 'dog', age: 6, name: 'cofee', parent: 4 },
];

function categorizePets(pets) {
  const categories = Array.from(new Set(pets.map((pet) => pet.type)));
  return categories.map((c) => {
    const parent = pets.find((pet) => pet.type === c);
    parent.children = pets
      .filter((p) => p.id !== parent.id && p.type === c)
      .map((p) => ({ ...p, parent: parent.id }));
    return parent;
  });
}

console.log(categorizePets(pets));

Create a function to categorize pets based on their type.

Answer №2

Could this be the solution?

const data = [
  { id: 1, animal: 'cat', age: 6, name: 'loky' },
  { id: 2, animal: 'cat', age: 3, name: 'michu', parent: 1 },
  { id: 3, animal: 'cat', age: 2, name: 'boots', parent: 1 },
  { id: 4, animal: 'dog', age: 9, name: 'bones' },
  { id: 5, animal: 'dog', age: 6, name: 'chok', parent: 4 },
  { id: 6, animal: 'dog', age: 6, name: 'cofee', parent: 4 },
];

function organizeHierarchy(arr) {
  const parents = data.filter((item) => !item.parent);
  const children = data.filter((item) => item.parent);
  return parents.map((parentItem) => {
    return {
      ...parentItem,
      children: children.filter((child) => child.parent === parentItem.id),
    };
  });
}
console.log(organizeHierarchy(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

Hiding the keypad on an Android device in an Ionic app when user input is detected

I am currently utilizing the syncfusion ej2 Calendar plugin for a datepicker, but I am only using options such as selecting ranges like today, 1 month, or last 7 days from the plugin itself. The plugin provides dropdown options when the calendar is trigger ...

Ways to refresh a page after clicking a button inside the modal box

As a beginner in PHP and JavaScript, I am facing an issue with refreshing the page view_create_journals.php when clicking on the change button in the modal. I have added a function to the change button but it doesn't seem to be working. I'm reall ...

The data from the server is inaccessible to node.js

I am a beginner in nodejs and jquery, trying to retrieve data from a server and use it to update a webpage: Using jquery on the client side: I would like to change the text inside '#info' element with the data fetched from the server. $('# ...

Responsive left and right image styling in CSS and HTML

I have designed a landing page with fixed left and right images and content in the middle. It looks fine on desktop view, but on mobile view, the images are overlapping the content. How can I resolve this issue? <div class=" ...

In Lua, we can print the heart symbol ( ♡ ) after successfully parsing a JSON data

Here is the function I have created, utilizing lua-cjson which claims full UTF-8 support. function getPersonaName(sid64) local cjson = require "cjson" local r = http.request("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=###&ste ...

Swap the < symbol with &gt; and & with &amp; within a specific node or location in an XML document

Hello everyone, I have a XML file with a node named Section, where certain characters like & and < are treated as invalid. I need to replace < with &lt; and & with &amp; only within the Section Node. Currently, I am using the following Java ...

AJAX File Upload: Sequentially Queuing Multiple Files

I am a beginner in the world of Javascript and jQuery. When I try to upload multiple files through a form, only the last file gets uploaded repeatedly. My goal is to upload each file one by one using AJAX requests asynchronously. Here's how I have ...

Jquery refuses to load

Hey everyone! I'm currently working on an HTML file for my Angular 2 course. After setting up the dependencies and downloading them with npm, I encountered an error when trying to run the app... The error message I received was: file:///Users/Rocky/A ...

Is it possible to organize multiple tables within a single JSON structure without relying on JArray?

I am currently developing a program similar to IMDB, where I am showcasing individuals with a filmography, discography, and more. After setting up my view in MVVM, I am now working on serializing my JSON data to align with it. At the moment, I am consolida ...

Streamline a javascript code with numerous elements

Seeking assistance in simplifying this code Currently, I find myself constantly updating this code each time a new entry is uploaded. I am looking for a solution where there is a single script that can identify the element IDs ("#rolly" or "#lagrimas") a ...

Releasing memory allocated for struct.name (warning: HEAP CORRUPTION IDENTIFIED)

Having an issue while attempting to free memory allocated with malloc in dynamic arrays created based on the length of a user-inputted name. The "Debug error" occurs when I try to use the free() function. typedef struct { char *nombre; float nota; ...

Node.JS function using try catch block

Is the following function suitable for use with Async Node.JS? I am wondering if it is written correctly, whether errors will be handled properly, or if it has been incorrectly implemented in terms of Async Node.JS. If there are issues with the implemen ...

Adapt appearance according to the length of the text

Currently, I have an array that stores multiple strings based on displayed charts. My objective is to find the longest string within this array. So far, this task has been executed without any issues. The code snippet for this process is as follows: var ...

What is the method for getting js_xlsx to include all empty headers while saving the file?

In the midst of developing a Meteor App, I've incorporated the Node.js package known as "js_xlsx" from "SheetJS", produced by "SheetJSDev". This tool enables me to convert an Excel sheet uploaded into JSON on the backend. The intention is to store thi ...

Mapping a JSON object to a mongoose schema's unique identifier ( _id )

Seeking assistance as I couldn't find a solution through keyword searches. Currently learning about mongoose and Node.js. Here is an example of the JSON post I am working with: { "_id": "711015", "is_in_violation": true, "is_occupied": true, ...

A method of submitting by simply pressing the enter key alongside clicking on a Bootstrap button

Here is the HTML code I am using to input prompts into a chatbot: <div class="input-group mb-3"> <input type="text" class="form-control" id="chat-input"> <div class="input-group-append ...

Prevent the box from closing automatically after submitting a form using jQuery

Despite my efforts to keep a simple dialog box open after submitting a form, it continues to close. I tried using the preventDefault method in jQuery, but it didn't solve the issue. Below is the code snippet: $(document).ready(function(e) { $(&apo ...

scope.$digest completes before triggering scope.$watch in Karma unit tests

I am interested in testing this specific directive: .directive('uniqueDirective', function () { return { restrict: 'A', scope: { uniqueDirective: '@', tooltip: '@', placement: '@&apo ...

Difficulty with the increment of my counter when using addeventlistener

I'm currently facing a challenge that I can't seem to figure out... Here is the issue (in JavaScript): export default { name: "TodoList", data() { return { title: "", content: null, isDone: true, count: 0, n ...

What is the process of connecting JSON keys to one another?

I am currently brainstorming a solution to link two distinct JSON formats with their respective keys. Here are the two formats: { "price": [ 511, 499, 419, 312 ], "paid": "OK", "contract": "year", "begindate": "01/01/2018", " ...