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 :
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);