Show the JSON data items in a React Native application

In my React Native application, I am dealing with a JSON file containing various data sets. One of the challenges I am facing is extracting specific information from this JSON and displaying it correctly.

[
  {
    "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"
      }
    ]
  }
]

I have attempted to extract the keys and cities from each object without success. The goal is to display these keys in a Picker element and then show the corresponding cities in a separate DropDown element when a key is selected.

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,
  }));
});

If anyone could help me correct this issue and make the data extraction process work as intended, it would be greatly appreciated.

Answer №1

Transform the source data structure into a usable format. For instance,

const data = [{"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"}]}];

const keys = data.flatMap(Object.keys);
const keyCityMap = Object.fromEntries(
  data.map((obj) =>
    Object.entries(obj).flatMap(([key, arr]) => [
      key,
      arr.map(({ city }) => city),
    ]),
  ),
);

console.log('keys:', keys);
console.log('keyCityMap:', keyCityMap);
.as-console-wrapper { max-height: 100% !important; }

Afterwards, utilize keys to navigate your selector choices and access the city array by using keyCityMap[selectorChoice].

This assumes that each key appears uniquely in the data array. However, it's unclear why data is an array to begin with.


If you require more than just the city name, consider using this alternative method to map the entire object

const keyCityMap = Object.fromEntries(
  data.map((obj) => Object.entries(obj).flat()),
);

Answer №2

To efficiently filter an array, you must use the Array Filter method

data = [{
    '001': [{
        index: 0,
        fare: 0.0,
        city: 'Colombo',
      },
      {
        index: 1,
        fare: 30.0,
        city: 'Maligawaththa',
      },
      {
        index: 2,
        fare: 38.0,
        city: 'Kelanithissa',
      },
      {
        index: 3,
        fare: 50.0,
        city: '4 Kanuwa / Biyagama road',
      },
      {
        index: 4,
        fare: 61.0,
        city: 'Thorana Junction',
      },
      {
        index: 5,
        fare: 73.0,
        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',
      },
    ],
  },
];

const keys = data.map((item) => Object.keys(item)[0]);
console.log("keys : ", keys);

const selectedKey = keys[0];

const cities = data.filter((item) => item[selectedKey])[0][selectedKey];
console.log("cities : ", cities);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Every time I attempt to execute mupx deploy, an error message appears

issue in console shubhabrata@shubhabrata-VirtualBox:~/Meteor/myapp$ mupx deploy Meteor Up: Advancing Meteor Deployments for Production Configuration file : mup.json Settings file : settings.json “ Discover Kadira! A powerful tool to monitor yo ...

Error: Mongoose validation issue - Unable to cast value "[ 'glass' ]" to an array for the field "materials"

Below is the makerSchema var makerSchema = new mongoose.Schema({ supplies:[{ material:{ type: String, required:[true, "Material is a required field"], trim:true, lowercase:true, enum: ...

What is the best way to iterate through curl and dynamically assign values in an API request?

Goal: How can I iterate through a curl statement and insert key value pairs into a put statement? Input: I have my SQL query result in JSON format. For example, I have mentioned two columns below: [{'brand_id': 1, 'brand_name': 'E ...

I am on a quest to locate a specific key within an array of objects and then validate it using Regex

I've been struggling with this for over 3 days and still haven't found a solution. It feels like trying to find a needle in a haystack, but I'm determined to figure it out. My goal is to search for a specific key in an array of objects and ...

Creating a Jasmine test for the event.target.click can be accomplished by defining a spec that

I need help creating a Jasmine test spec for the following method in my component. Here is my Component Method methodName(event): void { event.preventDefault(); event.target.click(); } I have started writing a test but don't fully cover event. ...

The property 'licenses' has incompatible types. The type 'License[]' cannot be assigned to type 'undefined' in the getServerSideProps function while using iron-session

I am encountering an issue with red squiggly lines appearing on the async keyword in my code: Argument of type '({ req, res }: GetServerSidePropsContext<ParsedUrlQuery, PreviewData>) => Promise<{ props: { admin: Admin; licenses?: undefined ...

Linking a string value to a specific data structure in TypeScript

I'm currently exploring typescript and I have a question about mapping a string value to a custom type when using templates in function calls. For instance: object.method<TypeMapper['CustomType']>([...]) In this scenario, 'Cust ...

Tips for generating cautionary claims in Playwright TypeScript assessments for non-urgent issues?

Is there a way to implement warnings instead of failures for non-critical assertions in Playwright TypeScript tests? Currently, while working on Playwright tests using TypeScript, I am searching for a solution to handle assertions that would issue warning ...

Converting an array of objects to an array based on an interface

I'm currently facing an issue with assigning an array of objects to an interface-based array. Here is the current implementation in my item.ts interface: export interface IItem { id: number, text: string, members: any } In the item.component.ts ...

Sharing specific calls from an established asp.net-mvc website with external REST clients on an internal network?

I currently have a functioning asp.net-mvc website and now I am seeking to make some of my internal calls available to external applications that are exclusively used within the site. This is all happening in an intranet setting within my organization. Af ...

A guide to locating a dynamic JSON array using the JSON Path Finder tool in Node.js

I am looking to extract some dynamic IDs from a JSON file using the JSON path finder in an npm package. Sample.json [ { "4787843417861749370": [ { "type": "Fast delivery", ...

The button's corners did not appear rounded after setting the borderRadius to '50%' in iOS

Does the same code round off buttons properly in Android but not in iOS? Is the percentage value not compatible with the iOS platform in React? import { TouchableOpacity, Text } from 'react-native'; export default class App extends React.Compone ...

A Java web application displaying the source code of my custom login page

I have a Java web application that publishes a service returning an object in JSON format. Another Java web app is set up to consume this service through a JSONP call and display the response. Everything works fine on my local machine, but when attempting ...

Error: The jasmine framework is unable to locate the window object

Currently, I am testing a method that includes locking the orientation of the screen as one of its functionalities. However, when using Jasmine, I encountered an error at the following line: (<any>window).screen.orientation.lock('portrait&apos ...

Issue with implementing generic inheritance for Repository in NestJS TypeORM: `this.function` is returning an error as it is not

I am attempting to create a specialized repository class that extends Repository in order to incorporate custom logging functions that can be utilized across all repositories. Here is the snippet of code: user.service.ts: @Injectable() export class UserSe ...

Having trouble connecting angular repository data with promise

I have been trying to implement the repository pattern in my Angular application. I can see that the JSON data is successfully retrieved over the network when I call my repository, but I am facing issues with binding it to my view. I have injected the rep ...

Transferring client-side data through server functions in Next.js version 14

I am working on a sample Next.js application that includes a form for submitting usernames to the server using server actions. In addition to the username, I also need to send the timestamp of the form submission. To achieve this, I set up a hidden input f ...

Unable to designate data types for a React Higher Order Component

In order to enhance a component with flattened props, I am working on creating a Higher Order Component (HOC). The goal is to take a component and return a new one that accepts flattened props using the flat package, then apply these unflattened props to t ...

No outcome when using Jquery and JSON

Check out my test code snippet here: http://jsfiddle.net/BjLdQ/2 I am trying to input the number 1 in each HTML field, click the login button, and receive the JSON response as: {"code":"2"} However, when I try to achieve the same using jQuery by clickin ...

steps for displaying JSON data in a table view

My goal is to extract data from a Json file, populate it in a table, and showcase it using an API call through Alamofire with a 'Post' request that includes parameters like the page number. I am interested in fetching the "results" from the foll ...