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?
Your solution has a decent start. There are only 2 problems with your solution:
const myData = {};
atts.forEach(att => {
if (myData[att.name]) {
myData[att.name].push(...att.data) // Notice this change
} else {
myData[att.name] = att.data;
// or if you don't want to alter the original data
myData[att.name] = [...att.data]; // basically a shallow copy
}
})
const result = [];
for (const key in myData) {
result.push({ data: myData[key], name: key });
}
console.log(result);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments