Search code examples
javascriptloopsnested-object

Grouping nested object properties


I have this nested Object:

{
  1: { one: { a: 5, b: 6, c: 7, d: 8 } },
  2: { one: { a: 6, b: 9, c: 10, d: 12, e: 1 } },
  3: { one: { a: 3, b: 4, c: 9 } },
}

Required output:

{
  one: {
    a: [5, 6, 3]
    b: [6, 9, 4]
    c: [7, 10, 9]
    d: [12]
    e: [1]
  }
}

Tried nested queries but failed.


Solution

  • Here's my take. A series of nested for for...in loops. Tried to optimize for readability.

    const object = {
      1: { one: { a: 5, b: 6, c: 7, d: 8 } },
      2: { one: { a: 6, b: 9, c: 10, d: 12, e: 1 } },
      3: { one: { a: 3, b: 4, c: 9 } },
    };
    
    const result = {};
    
    for (const group in object) {
      for (const num in object[group]) {
        if (!result[num]) {
          result[num] = {};
        }
        for (const letter in object[group][num]) {
          if (!result[num][letter]) {
            result[num][letter] = [];
          }
          result[num][letter].push(object[group][num][letter])
        }
      }
    }
    
    console.log(result)