Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

100
Views
ordenar el objeto anidado para que sea consecutivo y ascendente

Tengo un objeto anidado. Lo que estoy haciendo es agregar un nuevo objeto al objeto principal y luego eliminar uno de los objetos anidados y funciona bien. Lo que estoy tratando de hacer es una vez que elimino uno de los objetos anidados, quiero ordenar el resto en orden ascendente pero también cambiar el nombre de las claves para que sean consecutivas. Para explicarlo mejor, digamos que una vez que elimino un objeto anidado, mi objeto principal es este { 0: {}, 1: {}, 3: {}} , lo que significa que se eliminó la clave 2 objeto anidado, ahora lo que quiero es cambiar las claves ser { 0: {}, 1: {}, 2: {}} para que sean ascendentes y consecutivos. Gracias por adelantado.

 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 answers
Answer question

0

Si desea una estructura de datos cuyas claves enteras comiencen en 0 y no tengan huecos, debe usar una matriz, no un objeto; entonces todo lo que necesita hacer es separar el valor de la matriz, y el resto será re- arreglado apropiadamente. Empujar un valor también se vuelve mucho más fácil.

 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 Report

0

Estoy de acuerdo, no estoy seguro de que un objeto sea la herramienta adecuada aquí, sin conocer el fondo. Pero para responder a la pregunta como se publicó:

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!