Invert key value in js object

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts: 107

Invert key value in js object

I can't figure out how I can change the following object in JavaScript:

Code: Select all

{"first":["de"], "second":["ab","de"], "third":["de"]}
to:

Code: Select all

{"de":["first", "second", "third"], "ab":["second"]}
I want to associate unique values with list of containing keys in a JavaScript object.
Here is what I have tried:

Code: Select all

const data = {
  "first":["de"],
  "second":["ab","de"],
  "third":["de"]
}

console.log(
  Object
  .keys(data).reduce(function(obj, key) {
    obj[data[key]] = key;
    return obj;
  }, {})
)

Admin
You have to loop the array and for each item in the array check if an array for that value exists in the accumulator or not before adding it:

Code: Select all

const data = {
  "first":["de"],
  "second":["ab","de"],
  "third":["de"]
}

let result = Object.entries(data).reduce((acc, [key, arr]) => { // for each key-array of the original object
  arr.forEach(value => {                                        // for each value in the array
    acc[value] = acc[value] || [];                              // create an array in the output object if it doesn't already exist
    acc[value].push(key);                                       // push the key to it
  });

  return acc;
}, {});

console.log(result);
I also used Object.entries with each entry desctuctured as [key, arr] so I don't have to use the extra [key] to get the array while using Object.keys.

Similar Topics