2016-06-20 9 views
-4

Javascript Array Push-AusgabeJavascript Array hinzufügen oder aktualisieren

Ich habe ein Objekt:

people: [{name: peter, age: 27, email:'[email protected]'}] 

Ich möchte drücken:

people.push({ 
     name: 'John', 
     age: 13, 
     email: '[email protected]' 
}); 
people.push({ 
     name: 'peter', 
     age: 36, 
     email: '[email protected]' 
}); 

Die schließlich ich will, ist:

people: [ 
{name: 'peter', age: 36, email:'[email protected]'}, 
{name: 'john', age: 13, email:'[email protected]'}, 
] 

Ich habe keinen Schlüssel, aber die Emai l ist eine einzigartige

+1

Was ist das Problem? Doppelte Einträge? –

+0

Alles sieht korrekt aus, außer nachkommendem Komma im resultierenden Array –

+1

http://stackoverflow.com/help/how-to-ask – dabadaba

Antwort

1

Es gibt keine "update" -Methode wie in JavaScript.

Was Sie tun müssen, ist einfach durch Ihr Array zuerst zu durchlaufen, um zu prüfen, ob das Objekt bereits drin ist.

function AddOrUpdatePeople(people, person){ 
    for(var i = 0; i< people.length; i++){ 
     if (people[i].email == person.email){ 
      people[i].name = person.name; 
      people[i].age = person.age; 
      return;       //entry found, let's leave the function now 
     } 
    } 
    people.push(person);      //entry not found, lets append the person at the end of the array. 
} 
1

Sie können dies auch tun, indem Sie eine Array-Methode generieren. Es braucht zwei Argumente. Die erste bezeichnet das Objekt, das zu schieben ist, und die zweite ist die eindeutige Eigenschaft, die zu ersetzen ist, wenn ein zuvor eingefügtes Element existiert.

var people = [{name: 'peter', age: 27, email:'[email protected]'}]; 
 
Array.prototype.pushWithReplace = function(o,k){ 
 
var fi = this.findIndex(f => f[k] === o[k]); 
 
fi != -1 ? this.splice(fi,1,o) : this.push(o); 
 
return this; 
 
}; 
 
people.pushWithReplace({name: 'John', age: 13, email: '[email protected]'}, "email"); 
 
people.pushWithReplace({name: 'peter', age: 36, email: '[email protected]'},"email"); 
 
console.log(people);

Verwandte Themen