If I have an array of objects and there are certain objects that have the same name/property (in my case there are 2 instances of objects with a name of "highway"), how can I remove these objects from the array and add a new object with that contains data from both?
const data = [
{ "data": [ { "x": "sensor_error_code", "y": [ 0, 9 ] } ], "name": 123 },
{ "data": [ { "x": "road_type", "y": [ 15, 24 ] } ], "name": "city" },
{ "data": [ { "x": "road_type", "y": [ 0, 14 ] } ], "name": "highway" },
{ "data": [ { "x": "road_type", "y": [ 25, 30 ] } ], "name": "highway" },
{ "data": [ { "x": "weather", "y": [ 0, 8 ] } ], "name": "rain" },
{ "data": [ { "x": "weather", "y": [ 9, 24 ] } ], "name": "sun" },
{ "data": [ { "x": "special_object", "y": [ 5, 15 ] } ], "name": true }
];
e.g. having one instance of "highway" with a data object containing the values from both:
{ "data": [ { "x": "road_type", "y": [ 0, 14 ] }, { "x": "road_type", "y": [ 25, 30 ] } ], "name": "highway" }
So far I've tried to make a new empty object and loop over the data array, accumulating that empty object with names and values from that array. I was planning on converting that object to an array in the end. The code I've used is below:
const myData = {};
atts.forEach(att => {
if (myData[att.name]) {
myData[att.name].push(att.data)
} else {
myData[att.name] = att.data;
}
})
console.log(myData)
However, the code I've used above involves some additional manipulation to make the data ready for consumption by a library and I was wondering if there are simpler ways to achieve my goal?