I have this fiddle. All I want to do is , convert the values nested in each object literal to a string.
<ul data-bind="foreach: people">
<li>
<span data-bind="text: Name"> </span>
<span data-bind="text:Id"></span>
</li>
</ul>
function AppViewModel()
{
var self = this;
self.people = ko.observableArray([{"Name":"RobbStark",Id:1}, {"Name":"JohnSnow",Id:2}]);
}
ko.applyBindings(new AppViewModel());
I want to use a lookup like
var valueMap={
1:"SanJose",
2:"San Francisco"
}
To get output like
RobbStark SanJose
JohnSnow San Francisco.
How do I convert the observable to a different value inside foreach ?
All you have to do is call a javascript function from your text data-binding, passing in the current item ($data) from the for each loop as a parameter. Example fiddle
Javascript:
var valueMap={
1:"SanJose",
2:"San Francisco"
}
function AppViewModel()
{
var self = this;
self.people = ko.observableArray([{"Name":"RobbStark",Id:1}, {"Name":"JohnSnow",Id:2}]);
self.parsedName = function (item) {
return item.Name + " " + valueMap[item.Id];
};
}
ko.applyBindings(new AppViewModel());
HTML
<ul data-bind="foreach: people">
<li>
<span data-bind="text: $root.parsedName($data)"> </span>
</li>
</ul>
Note #1 under the KnockoutJS documentation contains more information about $data.