user2824374
user2824374

Reputation: 220

How can I map the array of objects inside an array and produce a result?

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?

Upvotes: 0

Views: 66

Answers (1)

MikeT
MikeT

Reputation: 5500

you can use a flatMap to convert an array of arrays into an array then you can use Object.fromEntires to convert an array of [key,value] into an object

so then all you need to do is unwrap your data

EDIT: Looks like i misread your requirements so here is a new version using a map instead of an object and some for loops rather than callbacks

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 map = new Map();

for (const car of cars) {
  for (const datum of car?.data ?? []) {
    if (!map.has(datum.id)) {
      map.set(datum.id, { data: datum, cars: [] });
    }
    map.get(datum.id).cars.push({
      id: car.id,
      name: car.name,
      model: car.model,
    });
  }
}

console.log(Object.fromEntries(map.entries()));

Upvotes: 1

Related Questions