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

92
Visualizações
sort nested object to be consecutive and ascending

I have a nested object. What I am doing is appending a new object to the main object then deleting one of the nested objects and it works fine. What I am trying to do is once I delete one of the nested objects I want to sort the rest by ascending order but also rename the keys to be consecutive. To explain that better say once I remove a nested object my main object is this { 0: {}, 1: {}, 3: {}} meaning nested object key 2 has been removed, now what I want is to change the keys to be { 0: {}, 1: {}, 2: {}} so that they are ascending and consecutive. Thanks in advance.

var myObject = {
  0: {
    "category": "myCategory1",
    "title": "myTitle1"
  },
  1: {
    "category": "myCategory2",
    "title": "myTitle2"
  }
}

const currentObjectKeys = Object.keys(myObject).sort();

const nextObjectKey = parseInt(currentObjectKeys[currentObjectKeys.length - 1]) + 1

myObject = Object.assign({
  [nextObjectKey]: {
    "category": "myCategory3",
    "title": "myTitle3"
  }
}, myObject)

delete myObject['1'];

//right here sort myObject by key then print myObject but say if the keys are 0 & 2
//I want to change the keys to 0 & 1 and this should work with any length of nested objects

console.log(myObject)

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

If you want a data structure whose integer keys start at 0 and do not have holes, you should use an array, not an object - then all you need to do is splice the value out of the array, and the rest will be re-arranged appropriately. Pushing a value becomes much easier too.

const categories = [{
  "category": "myCategory1",
  "title": "myTitle1"
}, {
  "category": "myCategory2",
  "title": "myTitle2"
}];

// instead of nextObjectKey and Object.assign, just do:
categories.push({
  "category": "myCategory3",
  "title": "myTitle3"
});

// instead of delete and resort, do:
categories.splice(1, 1);
// (index to remove, number of values to remove)
console.log(categories);

about 4 years ago · Juan Pablo Isaza Relatório

0

I would agree, not sure an object is the right tool here, not knowing the background. But to answer the question as posted:

const originalObject = {
  0: {
    "category": "myCategory1",
    "title": "myTitle1"
  },
  3: {
    "category": "myCategory3",
    "title": "myTitle3"
  },
  7: {
    "category": "myCategory7",
    "title": "myTitle7"
  }
};

const newObject = Object.fromEntries(
  Object.entries(originalObject)
    .sort(([k,v]) => k)
    .map(([k,v], i) => [i,v])
);

console.log(newObject);

about 4 years ago · Juan Pablo Isaza 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