Reputation: 67
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):
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.
Upvotes: 0
Views: 45
Reputation: 147216
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)
Upvotes: 1