I have create a knockout template .... How to get key and value from foreach in this template...
<!-- ko foreach: { data: getCouponCodes(), as: 'key => value' } -->
I need to get key and value
I have create a knockout template .... How to get key and value from foreach in this template...
<!-- ko foreach: { data: getCouponCodes(), as: 'key => value' } -->
I need to get key and value
If getCouponCodes
returns an array of objects, there's no "special" knockout way of getting the key(s) and value(s) of those objects directly in the binding.
In other words: you'll have to use plain javascript in either your view or viewmodel. There are many possible solutions, here are two to get you started:
computed
to transform the data to the desired format:const getCouponCodes = () => [ { name: "John" }, { name: "Kevin" } ]
ko.applyBindings({
couponData: ko.pureComputed(() =>
// Use whatever logic you require to return a viewmodel of "key" and "value"
getCouponCodes()
.reduce(
// You can also use: `for ... in`, `Object.keys`, etc.
// search for "Iterate over js object" to learn more
(data, coupon) => data.concat(Object.entries(coupon)),
[]
)
// Here we construct a simple viewmodel to make our data-binds easier
.map(([k, v]) => ({ key: k, value: v }))
)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<!-- ko foreach: couponData -->
<div data-bind="text: key + ': ' + value"></div>
<!-- /ko -->
Object.keys
and $parent
directly in your viewko.applyBindings({
getCouponCodes: () => [ { name: "John" }, { name: "Kevin" } ]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<!-- ko foreach: getCouponCodes() -->
<!-- ko foreach: Object.keys($data) -->
<div data-bind="text: $data + ': ' + $parent[$data]"></div>
<!-- /ko -->
<!-- /ko -->