如何在foreach中获得关键和价值

时间:2018-06-04 12:47:39

标签: knockout.js knockout-2.0 magento2.2

我创建了一个淘汰模板.... 如何从此模板中获取foreach的关键和值...

 <!-- ko foreach: { data: getCouponCodes(), as: 'key => value' } --> 

我需要获得关键和价值

enter image description here

1 个答案:

答案 0 :(得分:0)

如果getCouponCodes返回一个对象数组,那么就没有&#34;特殊&#34;敲除直接在绑定中获取这些对象的键和值的方法。

换句话说:您必须在视图或视图模型中使用纯JavaScript。有许多可能的解决方案,这里有两个解决方案:

首选:使用computed将数据转换为所需格式:

&#13;
&#13;
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 }))
  )
});
&#13;
<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 -->
&#13;
&#13;
&#13;

在您的视图中直接替代使用Object.keys$parent

&#13;
&#13;
ko.applyBindings({ 
  getCouponCodes: () => [ { name: "John" }, { name: "Kevin" } ]
});
&#13;
<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 -->
&#13;
&#13;
&#13;