Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a Map from an array of objects with a condition on array elements

I have an array of objects which i receive from a db:

[{
    key: 'PRODUCT',
    item_key: 'ITEM_01',
    sequence: 1
  },
  {
    key: 'STORE',
    item_key: 'STORE_01',
    sequence: 2
  }
]

I want to create a Map from it but the condition is, i want the item_key to be the map key, and only the corresponding array element which matches the item_key will be the value of that map key. So the map looks like

{
  'ITEM_01' => [{
    key: 'PRODUCT',
    item_key: 'ITEM_01',
    sequence: 1
  }],
  'STORE_01' => [{
    key: 'STORE',
    item_key: 'STORE_01',
    sequence: 2
  }]
}

I’ve kept the value of map keys as an array because there can be more values matching the map key in future. How can i do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

P.S. by Map i don’t mean the array function map, but the JS/TS Map

>Solution :

Use reduce to create an object, if the key exists in the object then push to the array, otherwise create an array and push the item:

const items = [{
    key: 'PRODUCT',
    item_key: 'ITEM_01',
    sequence: 1
  },
  {
    key: 'STORE',
    item_key: 'STORE_01',
    sequence: 2
  }
]

const result = items.reduce((obj, item) => {
  if (!obj.hasOwnProperty(item.item_key)) {
    obj[item.item_key] = [];
  }
  
  obj[item.item_key].push(item);

  return obj;
}, {});

console.log(result);

Here is an exmaple with Map:

const map = new Map();

const items = [{
    key: 'PRODUCT',
    item_key: 'ITEM_01',
    sequence: 1
  },
  {
    key: 'STORE',
    item_key: 'STORE_01',
    sequence: 2
  }
]

items.forEach(item => {
  if (map.has(item.item_key)) {
    map.get(item.item_key).push(item);
  } else {
    map.set(item.item_key, [item])
  }
});

console.log(Object.fromEntries(map))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading