Home > Blockchain >  How to transform maps: values to keys and merge another values to put them as an array inside that k
How to transform maps: values to keys and merge another values to put them as an array inside that k

Time:12-12

I need to merge 2 maps, transform some values to keys and bring another values to put them as an array inside those keys, e.g.:

From this maps:

const names= [
  { id: 1, name: 'JULIO FONTOVA' },
  { id: 2, name: 'CHRISTIAN JONES' },
  { id: 3, name: 'MARK DAVIES' }
];

const nexus = [
  { namesId: 1, phoNumbId: 1, country: PERU, mount: 1200 },
  { namesId: 1, phoNumbId: 2, country: CANADA, mount: 2000},
  { namesId: 2, phoNumbId: 2, country: ENGLAND, mount: 3000},
  { namesId: 2, phoNumbId: 3, country: RUSSIA, mount: 40000},
  { namesId: 3, phoNumbId: 1, country: BELGIUM, mount: 500},
  { namesId: 3, phoNumbId: 2, country: SPAIN, mount: 500},
  { namesId: 3, phoNumbId: 3, country: PORTUGAL, mount: 2020}
]

const phoneNumbers= [
  { id: 1, phoNumb: '111', name: 'JHON EVANS'},
  { id: 2, phoNumb: '222', name: 'JUDITH SOTO'},
  { id: 3, phoNumb: '333', name: 'OSCAR CIENFUEGOS'},
  { id: 4, phoNumb: '444', name: 'ANDREW JONES'}
]

I have tried many solutions, but none have worked. I would appreciate if someone could help me solve this. I'd like to transform them to something like this:

const mergedNumbers = [
  {JULIO FONTOVA : [111,222]},
  {CHRISTIAN JONES : [222,333]},
  {MARK DAVIES : [111,222,333]}
]

CodePudding user response:

That would do it:

const names = [
  { id: 1, name: "JULIO FONTOVA" },
  { id: 2, name: "CHRISTIAN JONES" },
  { id: 3, name: "MARK DAVIES" },
];

const nexus = [
  { namesId: 1, phoNumbId: 1, country: "PERU", mount: 1200 },
  { namesId: 1, phoNumbId: 2, country: "CANADA", mount: 2000 },
  { namesId: 2, phoNumbId: 2, country: "ENGLAND", mount: 3000 },
  { namesId: 2, phoNumbId: 3, country: "RUSSIA", mount: 40000 },
  { namesId: 3, phoNumbId: 1, country: "BELGIUM", mount: 500 },
  { namesId: 3, phoNumbId: 2, country: "SPAIN", mount: 500 },
  { namesId: 3, phoNumbId: 3, country: "PORTUGAL", mount: 2020 },
];

const phoneNumbers = [
  { id: 1, phoNumb: "111", name: "JHON EVANS" },
  { id: 2, phoNumb: "222", name: "JUDITH SOTO" },
  { id: 3, phoNumb: "333", name: "OSCAR CIENFUEGOS" },
  { id: 4, phoNumb: "444", name: "ANDREW JONES" },
];

const output = [];
for (const element of names) {
  output.push({
    [element.name]: nexus
      .filter((e) => e.namesId === element.id)
      .map((e) => phoneNumbers.find((f) => f.id === e.phoNumbId).phoNumb),
  });
}

console.log(output);

  • Related