Ad
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:
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.
Ad
Answer
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);
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad