Skip to content
Advertisement

Using map() or similar function to return the array data in the following format

I have the following javascript array (I’m having fun with map() today) – I want to be able to return the pages data but have the page id as the key and the index for the position of that page within the pages array as the value. What am I doing wrong?

let result = [
  {
      "id": 10000089,
      "units": [
          {
              "id": 10000200,
              "pages": [
                  {
                      "id": 100000882
                  }
              ]
          },
          {
              "id": 10000340,
              "pages": [
                  {
                      "id": 100000912
                  },
                  {
                      "id": 100000915
                  },
                  {
                      "id": 100000919
                  }
              ]
          }
      ],
  }
];
// this is my attempt but doesn't return in the intended format below
result.flatMap(el => el.units.map((e, i) => (e.pages)));

Expected output

pages = [
  100000882 => 0,
  100000912 => 0,
  100000915 => 1,
  100000919 => 2,
]

Here is a stackblitz to the code https://stackblitz.com/edit/js-mc9rqe

Advertisement

Answer

Your expected output should be an object instead of an array. You can use Array.prototype.flatMap, Object.fromEntries for achieving the result.

let result=[{id:10000089,units:[{id:10000200,pages:[{id:100000882}]},{id:10000340,pages:[{id:100000912},{id:100000915},{id:100000919}]}]}];

const pages = Object.fromEntries(
  result.flatMap(item => item.units.flatMap(unit => unit.pages.map((page,i) => ([page.id, i]))))
);
console.log(pages);

Note that, the Object.fromEntries() takes an array of arrays of a [key, value] pair and then converts them into an object. In your case the page.id would be the key and the index of the last map would be the value.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement