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

Javascript: Using Function Chaining to Rearrange Multidimensional Javascript Object

My title is slightly off, apologies, having trouble coming up with the right terms atm.

I am trying to do things functionally with .map(), .forEach(), etc.

I have a structure from a JSON like this, (all Items are unique strings, some contain spaces):

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

data = {
  Category1: ["Item_A", "Item_B", "Item_C"]
  Category2: ["Item_D", "Item_E", "Item_F"]
  Category3: ["Item_G", "Item_H"]
}

I would like this:

data = {
  Item_A: ["Category1"]
  Item_B: ["Category1"]
  Item_C: ["Category1"]
  Item_D: ["Category2"]
  Item_E: ["Category2"]
  Item_F: ["Category2"]
  Item_G: ["Category3"]
  Item_H: ["Category3"]
}

Thanks for any and all help.

>Solution :

You can iterate your data with Object.entries, using flatMap to replace each { key : array } pair with a flat array of [value, [key]] pairs, then use Object.fromEntries to create your desired output:

const data = {
  Category1: ["Item_A", "Item_B", "Item_C"],
  Category2: ["Item_D", "Item_E", "Item_F"],
  Category3: ["Item_G", "Item_H"],
}

const result = Object.fromEntries(
  Object.entries(data).flatMap(([k, a]) => a.map(v => [v, [k]]))
)

console.log(result)
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