0

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 enter image description here

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.

2
  • can you please provide a valid example of your data? The way you show it it is not clear if i.e NewYork and Paris are inside an array or object properties Commented May 19, 2022 at 7:04
  • @johnSmith I added a screenshot. Thanks for suggesting Commented May 19, 2022 at 7:13

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

I have a progress after applying your solution. But, I can not get the Keys of root keys. Updated the question and attached another screenshot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.