0

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

enter image description here

Mano M
  • 155
  • 1
  • 9
  • 2
    What key and value? Is `'key => value'` supposed to be PHP code? Show a meaningful sample of data, your viewmodel, explain what currently happens and what you expect to happen instead. – Tomalak Jun 04 '18 at 12:50
  • 0:{ name : "john" } 1: {name : "paul"}. I want to get the values of 'name ' and 'john' – Mano M Jun 04 '18 at 12:52
  • 1
    And the data is ... where? Again, post your code. – Tomalak Jun 04 '18 at 13:04
  • Please post your *code*. Not a badly cropped screenshot without any context. Post a working viewmodel. Actual code. Read [mcve]. – Tomalak Jun 04 '18 at 13:36

1 Answers1

1

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:

Preferred: use a 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 -->

Alternative Use Object.keys and $parent directly in your view

ko.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 -->
user3297291
  • 22,592
  • 4
  • 29
  • 45