简体   繁体   中英

How to access nested elements in array from the front-end using knockout JS?

I got a data from back-end and used parts of it in the front-end. It looks like this

    2021-22:
        NewYork: {PriceHeaders: Array(9), Comment: 'qwert', Pricings: Array(11)}
        Paris: {PriceHeaders: Array(2), Comment: null, Pricings: Array(3)}
    2020-21:
        Washington: {PriceHeaders: Array(19), Comment: 'fdsfdsf', Pricings: Array(121)}
        Berlin: {PriceHeaders: Array(21), Comment: null, Pricings: Array(143)}

number of elements and names of elements may change every time. My goal is to access every city in this list. Meaning : this code

data: Object.keys(pricings()), as: '_propertykey'

gives me 2021-22(and 2020-22 if I use it in foreach). I want to access NewYork, Paris etc.. Subelements.

div looks like this

  <div data-bind="foreach: { data: Object.keys(pricings()), as: '_propertykey', afterRender: tableRenderedHandler}">

  </div>

*pricings() is the list that contains all that data.

EDIT : I used console.log($context). This is the data displayed under $root在此处输入图像描述

UPDATE : As suggested, I changed my code like this :

 <div data-bind="foreach: { data: pricings(), as: '_propertykey', afterRender: pricingTableRenderedHandler}">
        <div data-bind="foreach: { data: Object.keys(_propertykey), as: '_propkey'}">
            <div data-bind="text: console.log($parent[_propkey])"></div>
            <div data-bind="text: console.log($parent[_propkey].Comment)"></div>

First log gives me whole object and second one is undefined.

So one way could be to just use nested foreach bindings

 # First iterate over the "root-keys 2021-22 ..."
  data-bind="foreach: pricings()"

    # Then iterate the keys of the "root keys"
    data-bind="foreach: Object.keys($data)" 

      # Then u can dynamically acces data from Paris, NewYork
      data-bind="text: $parent[$data].Comment"
      data-bind="foreach: $parent[$data].PriceHeaders"
      
      # To just print e.g "NewYork"
      data-bind="text: $data"

Another way would be to transform and flatten your data to arrays where no data is stored in keys

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM