Home > Net >  how can swap the key and array of values, of an object in JavaScript?
how can swap the key and array of values, of an object in JavaScript?

Time:10-25

This is my data:

obj = Object {
  Great Lakes: Array(3) ["Michigan", "Indiana", "Ohio"]
  Heartland: Array(2) ["Missouri", "Illinois"]
}

How can I change it to something like one by one:

{"Illinois": "Heartland", "Michigan": "Great Lakes", ...} 

I have to use Map, Object.entries and Array.flat().

I used : namemap = new Map(Object.entries(obj).map(function ([k, v]) {return [v, k];} )) but this is not I want or maybe this is not complete.

CodePudding user response:

Using map can do it,but first we need to make sure that we can access the array value correctly.

let data = {
  'Great Lakes':["Michigan", "Indiana", "Ohio"],
  'Heartland': ["Missouri", "Illinois"]
}

let result = {}
Object.keys(data).map(d1 => data[d1].forEach(d2 => result[d2] = d1))
console.log(result)

CodePudding user response:

Your code is almost correct, you just need to iterate the values in each array in obj:

const obj = {
  'Great Lakes': ["Michigan", "Indiana", "Ohio"],
  'Heartland': ["Missouri", "Illinois"]
}

const namemap = new Map(
  Object.entries(obj)
    .map(([k, a]) => a.map(v => [v, k]))
    .flat()
)

for (const [key, value] of namemap.entries()) {
  console.log(`${key} : ${value}`);
}

  • Related