user3346696 user3346696 - 23 days ago 7
jQuery Question

Remove item from JSON, 'reset' index from json obj - jquery

I want to remove a specific item from my JSON object, keep the rest of the object BUT, I want that the indexes of to 'recount' or something...

obj = {
"0":{
test: "test",
test: "test"
},
"1": {
test1: "test1",
test1: "test1"
},
"2": {
test2: "test2",
test2: "test2"
}
}


If I remove an item like

delete obj[1];


I do get the following:

obj = {
"0":{
test: "test",
test: "test"
},
"2": {
test2: "test2",
test2: "test2"
}
}


But I would like to have to have the obj with indexes 0 and 1. Because strange enough if I ask the .length of the result (after removing the item) it gives me 3 and I need the correct length in the rest of the application.

Anyone who knows what best practice is in this case?

Answer

If you cannot modify the structure of that data (which basically means turning it into an ECMAscript Array), you could hack around it a bit. Basically you could turn the Object into an ECMAscript Array.

obj.length = Object.keys( obj ).length;
obj.splice = [].splice;

Now you could treat it like an ordinary Array

obj.splice(1,1);

This would remove the element at position 1. You would need to restore the integrity of that object by removing the .length and .splice properties.

delete obj.length;
delete obj.splice;

That is probably not the most elegant solution, but it will do the job.

Comments