1

I have this javascript / jQuery code:

var json = [
    {
        id: 0,
        text: 'enhancement'
    },
    {
        id: 1,
        text: 'bug'
    },
    {
        id: 3,
        text: 'invalid'
    },
    {
        id: 4,
        text: 'wontfix'
    }
];



delete json[2]
console.log(json)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

This code delete the array key 2. But I need an reindex after that, so that I can access the other 3 values like:

json[0]
json[1]
json[2]

How can I realize this ?

3
  • Did you tried something? Commented Nov 9, 2021 at 12:39
  • 1
    You could try with json.splice(2,1); Commented Nov 9, 2021 at 12:39
  • json.filter(j => true) Commented Nov 9, 2021 at 12:40

4 Answers 4

2

Use splice instead of delete like below (W3schools splice):

json.splice(target_index,1);

Please read the Mozila page about the splice method for more information.

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

1 Comment

@Skully after using splice, OP can use json[0] - > json[2] and get expected result
0

If you don't want to mutate the value you can simply filter the array

json.filter((i, idx) => idx !== 2)

Comments

0

you can reindex by simply using

json.filter(function(){return true;})

here is a working demo.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#delete").click(function(){
   var json = [
    {
        id: 0,
        text: 'enhancement'
    },
    {
        id: 1,
        text: 'bug'
    },
    {
        id: 3,
        text: 'invalid'
    },
    {
        id: 4,
        text: 'wontfix'
    }
];



delete json[2]


console.log(json.filter(function(){return true;}))
  });
});
</script>
</head>
<body>
 <button id="delete">delete</button>
</body>
</html>

Comments

0

Splice method removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.

splice(start: number, deleteCount?: number)

json.splice(2, 1);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.