1

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?

2
  • sigh That's not JSON, it's just an object. Commented May 15, 2014 at 9:21
  • 1
    "Because strange enough if I ask the .length of the result (after removing the item) it gives me 3..." Not with that code it doesn't, it gives you undefined. Commented May 15, 2014 at 9:21

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Ok, I know this is not the most elegant and correct solution, but as you say it's a way to reach my goal. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.