Reason Reason - 4 months ago 20
Node.js Question

add/delete object in array

I have an array.

[
{
tab:0,
ip:'555.222.111.555',
stid:'sth'
},
{
tab:0,
ip:'123.321.231.123',
stid:'aaa'
},
]


Now I need to


  1. add
    +1
    to
    tab
    where
    ip
    is
    555.222.111.555
    .

  2. remove whole object where
    ip
    is
    123.321.231.123
    .


Answer

This is actually an array of objects not an array of arrays.

You can do something like this:

var arr = [  
  {  
     tab:0,
     ip:'555.222.111.555',
     stid:'sth'
  },
  {  
     tab:0,
     ip:'123.321.231.123',
     stid:'aaa'
  },
];

for(var i = arr.length-1; i >= 0; i--){
    if(arr[i].ip === "555.222.111.555"){
        arr[i].tab++; // increment tab by 1.
    }else if(arr[i].ip === "123.321.231.123"){
        arr.splice(i,1); // delete this object.
    }
}
console.dir(arr);