Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading