-1

Is it possible to map an array of objects with custom keys? Here's the outcome that I would like to have:

{ 4: Hotel, 3: Mall, 2: Resort, 1: Restaurant, 5: Staycation, 6: Store }

What I got:

[ "4: Hotel", "3: Mall", "2: Resort", "1: Restaurant", "5: Staycation", "6: Store" ]

The code:

// this data actually comes from a database

const categories = [
  { id: 4, name: "Hotel" },
  { id: 3, name: "Mall" },
  { id: 2, name: "Resort" },
  { id: 1, name: "Restaurant" },
  { id: 5, name: "Staycation" },
  { id: 6, name: "Store" },
];


console.log(
  categories.map((category) => {
    return category.id + ": " + category.name;
  })
)
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Larra
  • 346
  • 4
  • 14
  • `.reduce()` would be the easiest option. With `.map()` you would need a second step, e.g. `Object.fromEntries()` – Andreas Jan 04 '23 at 07:39
  • Also your map does nothing. You need to save the map to a variable: `const newCategories = categories.someArrayFunctionReturningSomething()` – mplungjan Jan 04 '23 at 07:43

1 Answers1

-1

Use reduce instead of map to keep the output to a single object instead of an array.

const categories = [
  { id: 4, name: "Hotel" },
  { id: 3, name: "Mall" },
  { id: 2, name: "Resort" },
  { id: 1, name: "Restaurant" },
  { id: 5, name: "Staycation" },
  { id: 6, name: "Store" },
];
// this data actually comes from a database

const c = categories.reduce((acc, category) => {
  acc[category.id] = category.name;
  return acc;
}, {});

console.log(c);
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
  • 2
    Why do you add an answer instead of VtC as obivous duplicate? – Andreas Jan 04 '23 at 07:41
  • I originally started answering the parsing of `[ "4: Hotel", "3: Mall", ... ]` to an object then found their actual mistake. Answering the question is more helpfulto new users than just saying "your post is a duplicate" and nothing more – Samathingamajig Jan 04 '23 at 07:44
  • _"...than just saying "your post is a duplicate" and nothing more"_ - If you think that's all what is happening when a question is closed as duplicate then you might want to have another look at the help section... – Andreas Jan 04 '23 at 07:45
  • Many a time have posts been marked as duplicate only for the OP to still be completely confused – Samathingamajig Jan 04 '23 at 07:45
  • Doesn't change the fact that a duplicate should be closed as such. That's why that option exists... Add a comment if you think OP needs further help. And your answer doesn't add anything useful that is not already available on any of those possible dupe targets. – Andreas Jan 04 '23 at 07:48