Tips for labeling an object value in javascript

I have a collection of objects organized by index and I want to rearrange them while adding categories to the output.

This is the initial collection:

let vehicles = [{'make': 'audi', 'model': 'RS3', 'transmition': 'automatic'}, {'make': 'audi', 'model': 'RS7', 'transmition': 'dual-clutch'}, {'make': 'bmw', 'model': '325is', 'transmition': 'manual'}, {'make': 'bmw', 'model': 'M2', 'transmition': 'dual-clutch'}]

Shown below is the code used to group the items by make:

var groupedByMake = _.groupBy(
          vehicles,
          "make"
        );

The resulting categorization is as follows:

{
  'audi':[{'model': 'RS3', 'transmition': 'automatic'}, {'model': 'RS7', 'transmition': 'dual-clutch'}],
  'bmw':[{'model': '325is', 'transmition': 'manual'}, {'model': 'M2', 'transmition': 'dual-clutch'}]
}

My objective is to format the outcome like this:

[{
  'make': 'audi',
   'types': [{'model': 'RS3', 'transmition': 'automatic'}, {'model': 'RS7', 'transmition': 'dual-clutch'}]
  },{
  'make': 'bmw',
  'types': [{'model': '325is', 'transmition': 'manual'}, {'model': 'M2', 'transmition': 'dual-clutch'}]
}]

If it's doable using JavaScript, could someone help me achieve this? Thank you.

Answer №1

If you want to transform one array into another and have the ability to decide whether to add a new element or update an existing one, you can leverage array.reduce method:

let cars = [{'make': 'audi', 'model': 'RS3', 'transmition': 'automatic'}, {'make': 'audi', 'model': 'RS7', 'transmition': 'dual-clutch'}, {'make': 'bmw', 'model': '325is', 'transmition': 'manual'}, {'make': 'bmw', 'model': 'M2', 'transmition': 'dual-clutch'}];

let output = cars.reduce((acc, cur) => {
    let {make, ...obj} = cur;    
    let prev = acc.find(x => x.make === make);
    if(!prev) {
      acc.push({make,types:[obj]})
    } else {
      prev.types.push(obj);
    }
    return acc;
}, []);

console.log(output);

Answer №2

const vehicles = [{'make': 'toyota', 'model': 'Camry', 'transmition': 'automatic'}, {'make': 'honda', 'model': 'Civic', 'transmition': 'manual'}, {'make': 'ford', 'model': 'F-150', 'transmition': 'automatic'}, {'make': 'chevrolet', 'model': 'Silverado', 'transmition': 'dual-clutch'}];
const categorizeBy = (array, key) => {
  return array.reduce((acc, item) => {
    const keyValue = item[key];
    const existingCategory = acc.find((category) => category.key === keyValue);
    if (existingCategory) {
      existingCategory.items.push(item);
    } else {
      // exclude make from item
      const { make, ...rest } = item;
      acc.push({ key: keyValue, items: [rest] });
    }
    return acc;
  }, []);
}


console.log(JSON.stringify(categorizeBy(vehicles, 'make'), null, 2));

Answer №3

To maintain your groupby with lodash:

  // Using the lodash library
var groupedByMake = {
  'audi':[{'model': 'RS3', 'transmition': 'automatic'}, {'model': 'RS7', 'transmition': 'dual-clutch'}],
  'bmw':[{'model': '325is', 'transmition': 'manual'}, {'model': 'M2', 'transmition': 'dual-clutch'}]
}

const result = Object.keys(groupedByMake).map(make => ({make, types: groupedByMake [make]}));

console.log(result);

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

Loading screen for specific content within the current WordPress theme

I am trying to display a preloader only in the 'content' div, but it ends up hiding the entire page. The structure of the site is as follows: Title Menu Content (where I want the preloader) Footer I'm having trouble figuring out where exa ...

JavaScript encountered an issue when trying to display HTML content

Through my PHP code, I am attempting to create a popup window that displays the content of an HTML file. However, after adding script tags, no HTML content is displayed. When I tried echoing out $row2, only the word 'array' appeared on the screen ...

Steps for adjusting the length in the getRangeLabel function of mat paginator

@Injectable() export class MyCustomPaginatorIntl extends MatPaginatorIntl { public getRangeLabel = (page: number, pageSize: number, length: number): string => { if (length === 0 || pageSize === 0) { return `${ ...

Retrieve the identification of elements with dynamically generated ids

I've dynamically generated a set of elements using Handlebars, as shown below {{#floor as |room i|}} <div class="btn-group-toggle" data-toggle="buttons" > <label class="btn btn-secon ...

JavaScript pop-up purchase tooltips from MenuCool

I am relatively new to the world of web design and programming. I am putting in a lot of effort to learn as much as possible, but I am encountering difficulties with the tooltip JavaScript that I incorporated into my website Click here to visit my website ...

Identifying and Blocking Users from Accessing External Domains Outside of the Angular Application

I am working on an angular application and I need to implement a feature where I can detect when a user navigates outside of the app domain from a specific component. For instance, let's say the user is on the upload component processing important in ...

The code seems to be malfunctioning in a separate JS file, but oddly enough, it functions properly when placed within a <script> tag

I am trying to create a loader, but I have encountered an issue where the script works when placed directly in the HTML file, but not when it is in a separate JavaScript file. Here is the script: var loader = document.getElementById("ld"); w ...

Troubleshooting Bootstrap 4: data-keyboard attribute malfunctioning

I am using a Bootstrap 4 carousel and have set the attribute data-keyboard="true" Unfortunately, the keyboard navigation feature is not working even when I focus on the carousel with the mouse first. I want the carousel to be interactive with t ...

Is there a way to access the original query string without it being automatically altered by the browser?

I'm currently encountering an issue with query strings. When I send an activation link via email, the link contains a query string including a user activation token. Here's an example of the link: http://localhost:3000/#/activation?activation_cod ...

Transforming JSON data for optimal rendering in ReactJS

I'm struggling with presenting nested JSON data on my website, even though it's successfully logging the data in the console. I am utilizing ReactJS and Axios for my API call. Below is a snippet of my code: import React, {useEffect} from "r ...

Transfer the content from a text area to a div element while keeping the original line breaks

I have a textarea and a div (containing a paragraph tag) where the content of the paragraph tag is updated with the text entered into the textarea upon keyUp. Is there a way to maintain line breaks from the textarea and have them appear as line breaks in ...

How can I bind the ID property of a child component from a parent component in Angular 2 using @Input?

I have a unique requirement in my parent component where I need to generate a child component with a distinct ID, and then pass this ID into the child component. The purpose of passing the unique ID is for the child component to use it within its template. ...

What are the steps to successfully host a socket.io server and an HTTP server simultaneously?

I have a situation where I have both a Socket.io server and a basic HTTP server that are working together, but the issue is that the HTTP server is trying to handle requests that should actually be handled by the Socket.io server. Below is the code snippe ...

What is the most efficient way to add or remove Date objects from arrays?

Struggling to update a calendar using the Datepicker component with Vue.js, I encountered some issues with adding and deleting items (specifically Date objects) I have written two javascript functions: one for adding new Dates to an array, and another for ...

Implement dynamic configuration injection by allowing users to specify the name of a configuration file during runtime, instead of having it fixed in the code

In my development using webpack, I am exploring ways to make my application configurations more dynamic. Presently, the project is a create-react-app that has been ejected. For instance, when creating a local build in my package.json file, I include the f ...

The program for determining the intersection of two arrays is reading in more elements than it was instructed to

I have encountered an issue with my C program that finds the intersection of two arrays. It seems that my array is not accepting the correct number of elements that I am trying to input. What could be causing this problem? Below is the code snippet in que ...

Ways to retrieve and upload a blob from a file object

After receiving a file object via an HTML input on-change event in my component.html: onFileSelected(event) { this.selectedFile = event.target.files[0]; } Now, I need to send a POST request to upload the image to the database. The database only acc ...

Guiding PHP on displaying specific comments under an article using AJAX

Currently, I'm in the process of constructing a news section for my website. However, I've hit a roadblock when it comes to displaying the appropriate comments using ajax... commentsLoad.php <?php include('config.php'); $newsid = ...

What are the steps to create a mirror image of an object within itself?

Can an object reflect itself? I am interested in seeing a self-reflection on a metallic object. In essence, the two rings of the mechanism should be reflected in the lower part. Thank you in advance! https://i.sstatic.net/m3KUY.jpg https://i.sstatic.n ...

Update the URL and content in Django dynamically

When accessing a json response from my Django backend via the URL /inbox/<str:username>, all messages in the conversation with that user are retrieved. The issue arises on the inbox page, where both threads and chatbox are displayed together, similar ...