Search code examples
javascriptarraysobject

Javascript sort object by key within nested objects


I have the following object:

{
  4: {
    1: [
      { order: 1, name: 'Test 4' }
    ]
  },
  0: {
    15: [
      { order: 7, name: 'Test 1' },
      { order: 3, name: 'Test 3' },
    ],
    12: { 
      { order: 1, name: 'Test 2' }
    }
  }
}

Essentially what I am trying to achieve is to order this by the keys and then order further by the order property from within the nested value. So in turn I get the following output:

{
  0: {
    12: { 
      { order: 1, name: 'Test 2' }
    },
    15: [
      { order: 3, name: 'Test 3' },
      { order: 7, name: 'Test 1' },
    ]
  },
  4: {
    1: [
      { order: 1, name: 'Test 4' }
    ]
  }
}

I then want to completely flatten this so it's without any of the outer object and just the data within the order, the outcome would then be:

[
  { name: 'Test 2' },
  { name: 'Test 3' },
  { name: 'Test 1' },
  { name: 'Test 4' }
]

I imagine this would be some kind of recursive operation which I need to do and I originally did it with something like the following but it got a bit messy:

Object.keys(obj)
  .sort()
  .reduce((acc, key) => { acc[key] = obj[key]; return acc; }, {});

Solution

  • Anotner one sorting approach

    const obj = {4:{1:[{order:1,name:'Test 4'}]},0:{15:[{order:7,name:'Test 1'},{order:3,name:'Test 3'},],12:[{order:1,name:'Test 2'}]}};
    
    const result = Object.entries(obj).flatMap(([u1, v1]) => 
        Object.entries(v1).flatMap(([u2, v2]) => 
            v2.map((v3) => ({ key: u1*1_000 + u2 + v3.order/1_000, item: v3 }))
        )
    )
    .sort(({ key: a }, { key: b }) => a - b)
    .map(({ item }) => item);
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0 }