Home > Enterprise >  jQuery reindex array
jQuery reindex array

Time:11-09

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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 ?

CodePudding user response:

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

json.splice(target_index,1);

CodePudding user response:

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

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

CodePudding user response:

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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

CodePudding user response:

A quick trick to remove all empty items is:

.filter(Boolean) 

What it does is it passes each item in the array to the Boolean() object, which coerces each item to true or false, and if true then keeps it. So this will remove every undefined, false, null, 0, and empty string ('') values from the array.

More information: Filter, Boolean.

Example

json = json.filter(Boolean)

With your code

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

delete json[2]
json = json.filter(Boolean)

console.log(json)
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related