I have a JSON file like the one below, and I am trying to use this data in a React native application.
[
{
"001": [
{
"index": 0,
"fare": 0,
"city": "Colombo"
},
{
"index": 1,
"fare": 30,
"city": "Maligawaththa"
},
{
"index": 2,
"fare": 38,
"city": "Kelanithissa"
},
{
"index": 3,
"fare": 50,
"city": "4 Kanuwa / Biyagama road"
},
{
"index": 4,
"fare": 61,
"city": "Thorana Junction"
},
{
"index": 5,
"fare": 73,
"city": "Kelaniya University"
}
]
},
{
"100": [
{
"index": 0,
"fare": "446.00",
"city": "Mulgampola"
},
{
"index": 1,
"fare": "452.00",
"city": "Kandy"
}
]
},
{
"101": [
{
"index": 0,
"fare": "446.00",
"city": "Mulgampola"
},
{
"index": 1,
"fare": "452.00",
"city": "Kandy"
}
]
}
]
And I need to display the keys of the each objects (001, 100, 101..) in a Picker
element and after user selects one of the options, I need to display the cities in a separate DropDown
element.
const keys = data.map((item) => Object.keys(item)[0]);
const cities = data.flatMap((item: any) => {
const routeNumber = Object.keys(item)[0];
return item[routeNumber].map((subItem: any) => ({
label: subItem.city,
value: subItem.index,
}));
});
I tried to access each object like above, and it does not work. Appreciate it if you could help me to correct this
2
Answers
You need to use Filter of Array
Map the source structure to something usable. For example
Then you can use
keys
to drive your picker options and lookup the array of cities usingkeyCityMap[pickerSelection]
.This assumes that each key only ever appears once in the
data
array. It’s not really clear whydata
is an array at all though.If you need more than just the city name, use this instead to map the entire object