How do I check whether my person has a knockout observable property called, say salary?
(emphasis mine)
If you use a check along the lines of if (ko.unwrap(person.salary))
, like the other answers suggest, you're basically checking if there's a defined salary
property.
I.e.:
person = { salary: undefined };
person = { };
person = { salary: ko.observable() };
Will all return true
for typeof ko.unwrap(person.salary) === "undefined"
If I take what you wrote literally, this doesn't answer whether the 'person' object has an observable property called salary
.
To answer this question, you'll need ko.isObservable
:
var persons = [
[{ }, "{ }"],
[{ salary: undefined }, "{ salary: undefined }" ],
[{ salary: ko.observable() }, "{ salary: ko.observable()" ]
]
var check1 = person => typeof ko.unwrap(person.salary) === "undefined";
var check2 = person => ko.isObservable(person.salary);
console.log(check1.toString());
persons.forEach(([p, c]) => console.log(c, "->", check1(p)));
console.log(check2.toString());
persons.forEach(([p, c]) => console.log(c, "->", check2(p)));
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
It might be that I took your question too literally, and all you need is ko.unwrap
, but I felt I had to share the difference