2016-07-16 116 views
0

我有一個數組。添加/刪除數組中的對象

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

現在我需要

  1. 添加+1tab其中ip555.222.111.555
  2. 刪除整個對象,其中ip123.321.231.123
+0

本發明的目的...去通過'陣列#splice'這樣做... – Rayon

+0

而找對象,'VAR發現= arr.find(函數(項目){ 退貨項目.ip =='555.222.111.555'; }); ++ found.tab;' – Rayon

回答

0

這實際上是一個不是數組數組的數組對象。

你可以做這樣的事情:

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

+0

感謝您的代碼工作完美。 – Reason

0

或者像這樣

var adresses = [ 
    { 
    tab : 0, 
    ip : '555.222.111.555', 
    stid : 'sth' 
    }, 
    { 
    tab : 0, 
    ip : '123.321.231.123', 
    stid : 'aaa' 
    } 
]; 
var results = adresses.filter((x) => x.ip != "555.222.111.555"); 
results.forEach((x) => {x.tab++}); 
console.log(results); // [ { tab: 1, ip: '123.321.231.123', stid: 'aaa' } ] 
0

你絕對可以嘗試這樣的:

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

 
// search the element in the existing array. 
 
function search(ip) { 
 
    for (var i = 0, len = a.length; i < len; i += 1) { 
 
     if (a[i].ip === ip) { 
 
     return i; 
 
     } 
 
    } 
 
    } 
 
    // adds an ip to the global storage. 
 

 
function add(ip, stid) { 
 
    debugger; 
 
    var index = search(ip); 
 
    if (index !== undefined) { 
 
     a[index].tab += 1; 
 
    } else { 
 
     a.push({ 
 
     tab: 1, 
 
     ip: ip, 
 
     stid: stid 
 
     }); 
 
    } 
 
    } 
 
    // remove the ip history from the storage. 
 

 
function remove(ip) { 
 
    var index = search(ip); 
 
    if (index !== undefined) { 
 
     a.splice(index, 1); 
 
    } 
 
    } 
 
    // adds a tab of this ip. 
 
add('123.321.231.123'); 
 
// removes the ip. 
 
remove('555.222.111.555'); 
 

 
console.dir(a);

+0

嘿@Reason請驗證並讓我知道你是否有顧慮。 – Ayan

+0

即時消息使用您的搜索功能,但即時消息不會測試代碼的其餘部分 – Reason

+0

偉大的人! @Reason如果這個部分是有用的,只需要投票。 :p和其餘代碼是爲了說明。您可以「運行代碼片段」來檢查其輸出。 – Ayan