2016-07-16 6 views
0

Ich habe ein Array.Objekt in Array hinzufügen/löschen

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

Jetzt muss ich

  1. hinzufügen +1-tab wo ip555.222.111.555 ist.
  2. das gesamte Objekt entfernen, wobei ip123.321.231.123 ist.
+0

Es ist ein Objekt ... Gehen Sie durch 'Array # splice' so zu tun ... – Rayon

+0

Und das Objekt zu finden,' var = arr.find (function (item) { Rückholeinzelteilrückseite .ip == '555.222.111.555'; }); ++ found.Tab; ' – Rayon

Antwort

0

Dies ist eigentlich ein Array von Objekten, nicht ein Array von Arrays.

Sie können etwas tun:

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

Danke Ihr Code funktioniert perfekt. – Reason

0

Oder so etwas wie dieses

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

könnten Sie auf jeden Fall wie folgt versuchen:

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

hey @Reason Bitte bestätigen Sie und lassen Sie mich wissen, wenn Sie Bedenken haben. – Ayan

+0

Im benutzen Sie Ihre Suchfunktion, aber ich tue nicht Rest des Codes – Reason

+0

Großer Mann! @Reason Gib einfach eine Stimme, wenn das Teil nützlich war. : p Und Ruhecode war für die Illustration. Sie können Code-Snippet nur ausführen, um die Ausgabe zu überprüfen. – Ayan