1

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 !

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hey, thanks a lot Jonas. Additionally, i observed that i have few records with values like this - "A": {"XY1" : [1,5]}. I would like to add it to the hash as 1: "A" and 5 :"A". I have made this edit - if(!(value instanceof Array)) hashTable[line][value] = station; else { value.map(item => { hashTable[line][item] = station; }) } Do u think there could be a cleaner way to this ?
Yeah, no need to .map if you dont need the return value ... Made an edit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.