Switching out nested loop within JavaScript

I've come across an array of objects that looks like this

let data = [
    {
        "id": 1,
        "name": "Sam",
        "father": true,
        "group": "orange"
    },
    {
        "id": 2,
        "name": "Alex",
        "father": true,
        "group": "red"
    },
    ...
]; 

The goal is to organize the data so that each father has their children listed in an array under a key named "members". The children should have the same color as their fathers. For example:

{
        "id": 1,
        "name": "Sam",
        "father": true,
        "group": "orange"
        "member":[
            {
                "id": 6,
                "name": "Oliver",
                "father": false,
                "group": "orange"
            }
       };
     // more examples 

I have implemented a solution using nested loops, but it's not very efficient and runs slow due to the complexity. Here is my current code:

function sorting(data) {
    data.forEach(fatherObjects => { 
        if (fatherObjects.father) {
            var member = [];
            data.forEach(childrenObjects => {
                if (!childrenObjects.father && childrenObjects.group === fatherObjects.group) {
                    member.push(childrenObjects)
                }
            });
            
            fatherObjects["member"] = member;
            console.log(fatherObjects);
        }
    });
}
sorting(data);

If you have any suggestions on how to make this process more efficient without sacrificing readability, please let me know.

Answer №1

To achieve this task, you can use a single loop with the help of the reduce method to group the items by their group property and use Object.values to obtain the desired outcome.

const result = Object.values(data.reduce((acc, i) => {
  if (!acc[i.group]) {
    acc[i.group] = {
      ...i,
      member: []
    }
  } else {
    acc[i.group].member.push(i);
  }
  return acc;
}, {}));

Check out the code in action:

let data = [{
    "id": 1,
    "name": "Sam",
    "father": true,
    "group": "orange"
  },
  {
    "id": 2,
    "name": "Alex",
    "father": true,
    "group": "red"
  },
  {
    "id": 3,
    "name": "Rock",
    "father": true,
    "group": "blue"
  },
  {
    "id": 4,
    "name": "Liam",
    "father": false,
    "group": "red"
  },
  {
    "id": 5,
    "name": "Noah",
    "father": false,
    "group": "red"
  },
  {
    "id": 6,
    "name": "Oliver",
    "father": false,
    "group": "orange"
  },
  {
    "id": 7,
    "name": "Sara",
    "father": false,
    "group": "blue"
  },
  {
    "id": 8,
    "name": "Max",
    "father": false,
    "group": "red",

  }
];

const result = Object.values(data.reduce((acc, i) => {
  if (!acc[i.group]) {
    acc[i.group] = {
      ...i,
      member: []
    }
  } else {
    acc[i.group].member.push(i);
  }
  return acc;
}, {}));

console.log(result);

Answer №2

function organizeFamily(data) {
  var newFamiliesArray=[];
    data.forEach(parentObjects => {
           if( parentObjects.parent ) {
             newFamiliesArray.push({
               ...parentObjects,
               children:[]
             });
           }
    });
    data.forEach(childObject => {
       if( !childObject.parent ) {
         newFamiliesArray.filter(f=>f.group===childObject.group)[0].children.push(childObject)
       }
    })

  return newFamiliesArray;
}
organizeFamily(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

Leverage the hidden glitch lurking within Vue

While working with SCSS in vue-cli3, I encountered a strange bug where using /deep/ would result in errors that I prefer not to deal with. Code Running Environment: vue-cli3 + vant + scss CSS: /deep/ .van-tabs__content.van-tabs__content--animated, .va ...

The Art of Determining the Text's Baseline

My goal is to create a test that determines whether the text rendered inside an <input> has the same baseline as a label: To achieve this, I want to calculate the baseline of the rendered text in each element and compare their values. Is it possible ...

Interactive webpages with dynamic HTML content, similar to the design of popular platforms such

Explore the source code of Dropbox's homepage or any Soundcloud page. They utilize various scripts and minimal pure HTML content (article, main, p, div). This method of generating pages is referred to as dynamic content/HTML. The main function seems ...

Using Golang to generate complex and nested JSON structures

I recently started learning Go and I've been struggling to find a way to output the unprocessed inner JSON "{\"data\":\"Some data"}" from "Outer". Unfortunately, I haven't had any success so far... This is the data provided: { ...

Transforming the elements within an array of objects into individual key-value pairs and then adding them to a fresh array

Hello, I am diving into the world of Typescript/Javascript and encountering some challenges when it comes to manipulating arrays of data. Please bear with me as I navigate through my learning curve. Imagine having an array of objects structured like this: ...

What seems to be the issue with the data initialization function not functioning properly within this Vue component?

In my Vue 3 component, the script code is as follows: <script> /* eslint-disable */ export default { name: "BarExample", data: dataInitialisation, methods: { updateChart, } }; function dataInitialisation() { return { c ...

Is there a way to store a class property as a variable using PostCSS?

Looking to store a dynamic property in a variable for use with calc(). There is a class with a height that changes dynamically. .cuerpo-detalle { height: x; } The goal is to create a variable that captures the height property of the .cuerpodetalle cla ...

Arrange an array of objects by making a nested API call in Angular

My task involves sorting an array of objects based on the response from the first API call in ascending order. The initial API call returns a list of arrays which will be used for the subsequent API call. The first API call fetches something like this: [0 ...

Shifting divs to different positions upon clicking

I am currently working on a project where I have three divs in a container positioned next to each other. My goal is to make them change their positions when clicked. For example, clicking on the left div should move it to the center position. Here is my p ...

When using @mouseover, it is not possible to modify a variable's value

The hover event is not functioning properly in this Vue component. Although I was able to call a function on hover successfully, I encountered issues when trying to change the hover variable directly. <template> <div @mouseover="hover = t ...

Error in inferring argument types for a generic interface function in Typescript

Unique interface export interface DataService { getByTypeId<T extends number | string>(id: T): Promise<SomeType>; } Additionally, the implementation export class BService implements DataService { async getByTypeId(id: number): Promise&l ...

Provide two values and complete the third one

I have a form with three input fields. I want to fill out two of the fields and have the third field automatically filled in. Here is how it should work: - I fill out the first and second fields, and the third field calculates itself - I fill out ...

What is the best way to enable an element to be dragged from just a single point?

I am facing a challenge with a parent div (such as "#strip17") that contains multiple child divs. Most of these child divs consist of a canvas where the user can draw using their mouse. However, the last child div should act as a handle that allows the use ...

Is it possible to create a struct that automatically transforms from serde_json::Value using Deserialize?

When it comes to deserializing from a string directly into a struct, everything works flawlessly. However, there are instances where you might already have a serde_json::Value and wish to convert it into a struct. For example, imagine you need to load a R ...

Executing multiple Ajax requests on CodeIgniter 3 from two separate pages

I am facing a critical need for a code review and unfortunately, I am unsure of where else to seek assistance besides here. Let me outline my current task: I am working on a user profile page that is designed to showcase users' comments. Users have t ...

What is the process for choosing with multiple attribute selectors?

Is there a way to disable multiple fields in a checkbox survey simultaneously? I attempted the following code, but it only works with one class. Is it possible to select by multiple classes within the same div? function surveyInit(){ $("div[class*=&apos ...

Struggling to interpret JSON using JavaScript and Ajax

I have a PHP script that generates a .json file: <?php $data=array( "Name"=>"John", "Surname" => "Doe"); $jsontext = "["; foreach($data as $key => $value) { $jsontext .= "{objectValue: '".addslashes($key)."', textObject: &apo ...

Creating a single object from the union of two arrays with JavaScript

I'm looking for a way to merge two arrays into a single object named "data" but haven't discovered an efficient method yet. Here are the arrays: var X = [ 4, 5, 6 ]; var Y = [ d, e, f ]; Merge them into an object: var data = { Y: [ d, e, f ], ...

Verify and send form without reloading the page

I am currently facing an issue with jQuery validation and ajax form processing. My goal is to prevent a page refresh by using ajax, but I am struggling to determine the appropriate placement for the ajax code within the validation function in order to ensu ...

Removing data using axios in a React project

I'm currently working on a small app using the Json server package to help me keep track of movies I want to watch in my free time. I am looking to learn React and Axios, so I decided to build this app with these technologies. The concept is simple - ...