Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

105
Visualizações
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; }, {});
about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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 }

about 4 years ago · Santiago Trujillo Relatório

0

The integer properties (in the range of 32 bit unsigned integers) don't need sorting, as iteration over them (e.g. via Object.values) is by specification already sorted by those integer keys. So the logic needs to focus only on sorting the inner objects, and it will be fine.

const flatSort = obj => Array.isArray(obj)
    ? [...obj].sort((a, b) => a.order - b.order).map(a => a.name)
    : Object.values(obj).flatMap(flatSort);

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 res = flatSort(obj);
console.log(res);

about 4 years ago · Santiago Trujillo Relatório

0

You can sort each obj by keys using Object.keys(obj).sort() and then access each element by its key.

Do this 2 times to get the array of object

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' }
    ]
  }
}

let flatItems = []
const keys = Object.keys(obj).sort()

for (const key of keys){
  const subObj = obj[key]
  
  const subKeys = Object.keys(subObj).sort()
  
  for(const subKey of subKeys){
   flatItems = flatItems.concat(subObj[subKey].sort((a, b) => a.order - b.order))
  }
}

console.log(flatItems)

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda