Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add a lable to an object value in javascript

I have an array of objects that is grouped by index and would like to restructure and add labels to the response.

This is my original array:

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'}]

Here is the source code used to group the array by make:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

The response looks like this:

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

My desired outcome should look 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'}]
}]

Is this possible to achieve using JavaScript? If so can I get assistance to achieve this task.

>Solution :

You can use array.reduce to turn one array into another one and control whether you return a new element or accumulate values in existing one (prev):

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading