I use KO JS and had an issue with displaying keys of the root keys. I asked a question about it and did have some progress but still, problem is not solved. LINK TO PREVIOUS QUESTION
I figured that my data needed mapping. Data that I get from back-end looks like this :

Here is text version of sample data
"Pricings": {
"2021-22": {
"Tbilisi": {
"PriceHeaders": [
],
"Comment": "TBi",
"Pricings": [
{
}
]
},
"2020-21": {
"Tbilisi": {
"PriceHeaders": [
],
"Comment": "TBi",
"Pricings": [
{
}
]
}
}
}
I'm thinking about recreating data like this : from :
2020-21 :
{
Tbilisi: {PriceHeaders: Array(9), Comment: 'TBi', Pricings: Array(1)}
}
To :
Year : 2020-21
Cities : {
Tbilisi: {PriceHeaders: Array(9), Comment: 'TBi', Pricings: Array(1)}
}
After that, I can run a simple foreach and get Values of Year and Any key from Cities.
I came up with something like this
Object.entries(data).map(([year, cities]) =>
(
{
"year": year,
"cities": Object.entries(cities).map(([name, cities]) =>
(
{
name,
...cities
}
))
}
))
Problem is, I can not make use of this code in data bind
<div data-bind="data : THIS FUNCTION HERE , as 'result'"></div>
This problem has been solved already with this answer
The key code is:
.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 }))
What this will do for your data is wrap the data you have already in a wrapper object, so with your example data it would compose...
{
key: "2020-21",
value: {
Tbilisi: {
PriceHeaders: Array(9), Comment: 'TBi', Pricings: Array(1)
}
}
}
...from your original structure
2020-21 :
{
Tbilisi: {PriceHeaders: Array(9), Comment: 'TBi', Pricings: Array(1)}
}
This means that when you iterate over the pureComputed function in your kojs template, you will be able to access year with [binding]: key and the nested data with [binding: value
You may also want to look into the 'mapping' plugin in knockout for the object values, to make it update when data is changed (unless it will always be static)