Search code examples
javascriptarraysobjectpromise

name an object in Array


I'm doing multiple fetchs with Promise.all. So I receive data like this :

[
   0: {
      ...
   },
   1: {
      ...
   }
]

But I would like to name my Objects. So I can do data.myObject istead of data[0].

I would like the index to be a string that I chose. For example, i'd like to get :

[
   "home": {
      ...
   },
   "product": {
      ...
   }
]

Is is possible ? Thanks


Solution

  • Seems like you want to convert Array to an object so you can get data by calling a key.

    const arr = [ { id: "home", val: "val1" }, { id: "product", val: "val2" }];
    const convert = arr.reduce((a,b) => (a[b.id] ??= b,a),{});
    console.log(convert);
    console.log(convert.home);