How to use knockout to iterate over an object (not array)

前端 未结 8 570
不知归路
不知归路 2020-12-04 23:31

I want to use something similar to the Knockout foreach construct to iterate over the properties of an object. Here is what I am trying to create...

DESIRED

8条回答
  •  星月不相逢
    2020-12-05 00:10

    In a modern browser (or with an appropriate polyfill) you can iterate over Object.keys(obj) (the method returns only own enumerable properties, meaning that there is no need for an additional hasOwnProperty check):

    Fiddled.

    NB: I was simply curious to see if this would work, the template body above is more polluted than what I'd like to use in production (or come back to a few months later and be like "wtf").

    Custom binding would be a better option, my personal preference though would be to use a computed observable or a writeable computed observable (the latter would be handy when working with json responses a-la restful api).

提交回复
热议问题