user4387602
user4387602

Reputation: 113

Grouping dynamic keys in array of objects

I have an object that i am trying to transform

var data = {
  "A": {"XY1" : 1},
  "B": {"XY2": 12},
  "C": {"XY3": 10},
  "D": {"XY1": 2}

am trying to transform this to

[
  { "XY1": { 1:"A", 2:"D"}},
  { "XY2": { 12:"B"}},
  { "XY3": { 8:"A", 10:"C"}},
]

(we can ignore the ordering of XY1, XY2 etc)

Here is what i have done so far -

  var result = Object.keys(data).flatMap(alphabet => {
    return Object.keys(data[alphabet]).map(group => {
      return Object.assign({}, {
        [group]: { [data[alphabet][group]]: alphabet }
      })
    });
  });

console.log(result);

which prints

[
  {"XY1":{"1":"A"}},
  {"XY3":{"8":"A"}},
  {"XY2":{"12":"B"}},
  {"XY3":{"10":"C"}},
  {"XY1":{"2":"D"}}
]

However, i want it to be grouped by using reduce(chaining), such as -

var result = Object.keys(data).flatMap(alphabet => {
  return Object.keys(data[alphabet]).map(group => {
    return Object.assign({}, {
      [group]: { [data[alphabet][group]]: alphabet }
    })
  });
}).reduce((obj, item) => {

});

Is this possible ? How do i group by these dynamic keys?

Help much appreciated !

Upvotes: 1

Views: 719

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138267

I'd group first using a hashtable:

  const hash = {};

   for(const [key, obj] of Object.entries(data)) {
     for(const [key2, values] of Object.entries(obj)) {
        if(!hash[key2]) hash[key2] = {};

        for(const value of [values].flat())
          hash[key2][value] = key;
     }
   }

To then get an array you can use Object.entries:

  const result = Object.entries(hash).map(([key, value]) => ({ key, value }));

This is not exactly what you wanted, but to be honest I don't see a sense of having an array of objects with just one key each.

Upvotes: 4

Related Questions