I'm trying to do an hashmap similar task here. Certainly feeling hard. USA is common for both Honda and Tesla, JAPAN for Honda and China for Hyundai. I've given an attempt here, but I feel like I'm overcomplicating things by doing map inside map.
const cars = [
{
id: 1,
name: 'Honda',
model: 2017,
data: [
{ id: 101, city: 'JAPAN' },
{ id: 102, city: 'USA' },
],
},
{
id: 2,
name: 'Tesla',
model: 2018,
data: [
{ id: 103, city: 'CHINA' },
{ id: 102, city: 'USA' },
],
},
{
id: 3,
name: 'Hyundai',
model: 2019,
},
];
const obj = {};
const arr = [];
cars.map((item) => {
if ('data' in item) {
item.data.map((ele) => {
obj.myCarId = {
data: { id: ele.id, city: ele.city },
cars: [{ id: item.id, name: item.name, model: item.model }],
};
arr.push(obj);
});
}
});
// Expected answer:
{
['101']: {
data:{ id: 101, city: 'JAPAN'},
car:[{id: 1,name: 'Honda',model: 2017}],
},
['102']: {
data:{ id: 102, city: 'USA'},
car:[{id: 1,name: 'Honda',model: 2017},{id: 2,name: 'Tesla',model: 2018}],
},
['103']: {
data:[{ id: 103, city: 'CHINA'}],
car:[{id: 3, name: 'Hyundai',model: 2019}],
},
}
How do I map my USA data with Honda and Tesla and produce output something like the above?
mapinside it to return tuples with[id, data]and then finally doObject.fromEntriesagainst the array.