Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

Firstly, change the object to an array:

obj = [ {
    test: "test",
    test: "test"
},{
    test1: "test1",
    test1: "test1"
},{
    test2: "test2",
    test2: "test2"
}]

Then you can use splice() to remove an element from the array:

obj.splice(1, 1); // removes the item at index 1

This saves you the need of having to reset the index as you can just use the ordinals of the array itself.

Example fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top