JSFiddle - React, Tailwind, and code Playground
HTML
<select data-bind="options: sampleObservableArray, optionsText: 'lastName', optionsCaption: 'choose...'"></select>
<br/>
<label for="_name">Name:</label><input id="_name"/><br/>
<label for="_lastName">Last Name:</label><input id="_lastName"/><br/>
<label for="_phone">Phone:</label><input id="_phone"/><br/>
<button data-bind="click: addPerson">Add person</button>
JavaScript
function Person(name, lastName, phone)
{
return {
name : ko.observable(name),
lastName : ko.observable(lastName),
phoneNumber : ko.observable(phone)
}
}
var vm = {
sampleObservableArray : ko.observableArray(),
addPerson : function()
{
var newPhone = document.getElementById("_phone").value,
newName = document.getElementById("_name").value,
newLastName = document.getElementById("_lastName").value;
var existentPerson = ko.utils.arrayFirst(vm.sampleObservableArray(), function(item)
{
return item.phoneNumber() == newPhone;
})
if (existentPerson)
{
existentPerson.name(newName);
existentPerson.lastName(newLastName);
existentPerson.phoneNumber(newPhone);
}
else
{
vm.sampleObservableArray.push(new Person(newName, newLastName, newPhone))
}
}
}
vm.sampleObservableArray.push(new Person("Ronald", "McDonald", "1"))
vm.sampleObservableArray.push(new Person("Michael", "McConnel", "2"))
ko.applyBindings(vm)