Classify the JavaScript objects according to the array of object lists

Struggling to find a solution for converting this list of objects based on the group array. The challenge lies in iterating through the group Array and applying the object to multiple places when there are several groups.

Additionally, trying to disregard any group that isn't associated with anything. Attempted using the reduce function but encountered difficulties with iterating through the group array.

  let cars = 
    [
      {
        "group":[],
        "name": "All Makes",
        "code": ""
      },
      {
        "group":["Group A"],
        "name": "BMW",
        "code": "X821"
      },
      {
        "group":["Group B"],
        "name": "Audi",
        "code": "B216"
      },
      {
        "group":["Group B"],
        "name": "Ford",
        "code": "P385"    
      },
      {
        "group":["Group B", "Group C"],
        "name": "Mercedes",
        "code": "H801"
      },
      {
        "group":["Group C"],
        "name": "Honda",
        "code": "C213"
      }
    ]

The desired outcome is:

let cars = {
    "Group A": [
      {
        name: "BMW",
        code: "X821",
      }
    ],
    "Group B": [
      {
        name: "Audi", 
        code: "B216"
      },
      {
        name: "Ford", 
        code: "P385"
      },
      {
        name: "Mercedes",
        code: "H801"
      }
    ],
    "Group C":[
      {
        name: "Mercedes",
        code: "H801"
      },
      {
        name:"Honda", 
        code: "C213"
      }
    ]
  };

Attempted using reduce method for this task but struggled with replicating grouping if an object belongs to more than one group.

let result = cars.reduce(function(x, {group, name}){
  return Object.assign(x, {[group]:(x[group] || [] ).concat({group, name})})
}, {});

Any suggestions to tackle this problem would be highly valued.

Answer №1

To iterate through each car object in the cars array, you can utilize the .reduce() method. Within this loop, you can use the .forEach() method to add each group as a key to the accumulator object. If the group already exists in the accumulator, you can retrieve the corresponding array of objects; otherwise, you can create a new empty array.

Here is an example illustrating this process:

const cars = [{ "group":[], "name": "All Makes", "code": "" }, { "group":["Group A"], "name": "BMW", "code": "X821" }, { "group":["Group B"], "name": "Audi", "code": "B216" }, { "group":["Group B"], "name": "Ford", "code": "P385" }, { "group":["Group B", "Group C"], "name": "Mercedes", "code": "H801" }, { "group":["Group C"], "name": "Honda", "code": "C213" } ];
          
const res = cars.reduce((acc, {group, ...r}) => {
  group.forEach(key => {
    acc[key] = (acc[key] || []).concat({...r}); // creating a copy of r for each grouped array
  });
  return acc;
}, {});
console.log(res);

Answer №2

Implementing a simple strategy. @Nick's method proves to be more effective.

let vehicles = [{
    "group": [],
    "name": "All Models",
    "code": ""
  },
  {
    "group": ["Group A"],
    "name": "Toyota",
    "code": "T821"
  },
  {
    "group": ["Group B"],
    "name": "Chevrolet",
    "code": "C216"
  },
  {
    "group": ["Group B"],
    "name": "Hyundai",
    "code": "H385"
  },
  {
    "group": ["Group B", "Group C"],
    "name": "Nissan",
    "code": "N801"
  },
  {
    "group": ["Group C"],
    "name": "Kia",
    "code": "K213"
  }
]
let newVehicles = {};
vehicles.forEach(item => {
  item.group.forEach(g => {
    if (!newVehicles[g])
      newVehicles[g] = [];
    newVehicles[g].push({
      name: item.name,
      code: item.code
    });
  });
});
console.log(newVehicles);

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

Submitting form data including file uploads using AJAX

Currently, the file is being sent via AJAX using the following code: var fd = new FormData(); //additional actions to include files var xhr = new XMLHttpRequest(); xhr.open('POST', '/Upload/' + ID); xhr.send(fd); In ...

How can I prevent the same JavaScript from loading twice in PHP, JavaScript, and HTML when using `<script>'?

Is there a PHP equivalent of require_once or include_once for JavaScript within the <script> tag? While I understand that <script> is part of HTML, I'm curious if such functionality exists in either PHP or HTML. I am looking to avoid load ...

Tips on generating a sample Mongoose Model with all null values

Imagine you are working with the following schema: var userSchema = new Schema({ name: String, schools: [{ level: String, name: String, timeInterval: { start: {type:Date,default:Date.now}, ...

A Promise-based value returned by a Typescript decorator with universal methods

I am currently working on creating a method decorator that can be applied to both prototype and instance methods. Referenced from: Typescript decorators not working with arrow functions In the code provided below, the instanceMethod() is returning a Prom ...

Utilizing accurate server URLs (Codeigniter) for local JavaScript execution

Help Needed: Issue with Correct Path Names in Local JavaScript with CodeIgniter Backend I am facing difficulties in using the correct path names in local JavaScript while working with a backend in CodeIgniter. -user_data -application -system -assets In ...

Using jQuery to create clickable images by enclosing them in an `<a>` tag

How can I make each image with a specific class clickable? I would like jQuery to: Retrieve the src attribute of the image. Enclose the image within an a href tag that includes that src URL. .clickable { padding: 20px; border: 1px ...

iOS devices featuring the scroll function allows for seamless navigation and effortless

Here is the code snippet that I am using: $(document).scroll(function() { thedistance(); }); I would like thedistance() to trigger while a user is scrolling on an iOS device, however, it currently only fires after the scrolling has stopped, rather t ...

Arranging data efficiently using Quicksort in C++

In my current school project, I have been tasked with sorting an array. After researching different algorithms, I decided to go with quicksort since it's a method that I'm not yet familiar with. Thankfully, I was able to grasp how it functions an ...

What is the best way to transform the pages extracted through the Notion API into slugs?

I'm new to Next.js and Notion API, and I want to create a blog site on my personal website using the Notion API. While I can easily pull the posts, I am facing a challenge in slugifying the endpoint IDs with post titles. When attempting this based on ...

Accessing form data using Vue on submit

I'm working on a project that involves creating a form with a single input field and saving the data to a database. The technology I am using is Vue.js. Here is the template I have designed: <form class="form-horizontal" @submit.prevent="submitBi ...

Guide on sending a JavaScript function to a Pug file using Node.js and Express

In my recent project, I developed a node app using express along with a pug file. The express app is configured to listen on port 3000 and render the pug file. One of the key functionalities involves fetching information from an external API. My goal is to ...

After extended periods of use, the website experiences frequent crashes

Currently, I am developing a website using a free provider (000webhost) and focusing on integrating a chat feature. To achieve this, I have implemented an interval every 500 milliseconds that reads a file to check for new messages. When a new message is de ...

How to toggle tooltip visibility dynamically using Angular 2

I am working with elements within an ngFor loop. Some of these elements have tooltips, while others do not. I am experiencing an issue where when using the code snippet below: <div ngFor="let item of items"> <div [title]="item.title"> Ele ...

Creating JSON data in PHP is a straightforward process that involves encoding

I am looking to generate a JSON output that looks like this: { "id": "c200", "name": "Aneesh", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86e7e8c6e1ebe7efeaa8e5e9eb">[email protected]</a> ...

A guide to efficiently passing props in Quasar 2 Vue 3 Composition API for tables

I am encountering an issue while attempting to create a custom child component with props as row data. The error message "rows.slice is not a function" keeps appearing, and upon inspecting the parent data, I found that it is an Object. However, the props r ...

What could be causing my div element to remain stationary despite the movement functions I have implemented?

I am attempting to move my div element by using key presses to adjust the CSS attributes of the HTML elements. However, despite implementing the necessary code, the mover refuses to budge and nothing appears when I inspect the elements or their attributes. ...

Is there a way to postpone the execution of a scheduled interval function?

Below is the setup of my function: setInterval(function () { get_fb(); }, 10000); If a user interacts with an element, such as hovering over it or clicking on it, I want to reset the timer back to 10 seconds. How can I instruct the program to achieve th ...

Transferring cookies across subdomains

I am facing an issue with an ajax request going from one subdomain to another, for example from sub1.example.com to sub2.example.com. Despite having a cookie set for all domains (cookie domain='.example.com'), the cookie is not being sent to the ...

Ways to capture targeted requests

Utilizing NestJS and Angular 2, I have noticed that both frameworks have a similar approach when it comes to working with Interceptors. I am currently looking for the best practice to identify specific requests in order to perform additional tasks. When d ...

Creating a scale effect similar to iCloud.com in Angular.JS: A step-by-step guide

Have you checked out the new icloud.com site? There's a cool effect on there that I want to try and recreate for a project I'm working on. When you go to and log in, you'll notice a loading gif followed by the calendar app scaling out to t ...