Tips for populating a Flat List with nested JSON data in React-Native

As a beginner in React-Native and Javascript, I'm trying to figure out how to retrieve data for my FlatList. The JSON format I receive is structured like this:

[
  {
    "18": {
      "sellingUnitName": "unité(s)",
      "qualifier": "GOOD",
      "sizeQualifierName": "gr.20"
    },
    "19": {
      "sellingUnitName": "unité(s)",
      "qualifier": "BAD",
      "sizeQualifierName": "gr.18-20"
    }
  }
]

This is what my FlatList currently looks like:

<FlatList
    data={ this.state.dataSource }
    ItemSeparatorComponent = {this.FlatListItemSeparator}
    renderItem={({item}) => <Text>{item.sellingUnitName}</Text>}
    keyExtractor={(item, index) => index.toString()}
/>

The FlatList works well with the simpler format shown below:

[
  {
    "sellingUnitName": "unité(s)",
    "qualifier": "GOOD",
    "sizeQualifierName": "gr.20"
  },
  {
    "sellingUnitName": "unité(s)",
    "qualifier": "BAD",
    "sizeQualifierName": "gr.18-20"
  }
]

My question is: How can I access the values in the first nested format by looping through each item and ignoring the first id (for example "18" in the first example)? I want to be able to use item.keyName in my FlatList to display each value but I am struggling to access the nested elements.

Additionally, here's how I fetch my data:

fetch('https://www.mywebsite.com/test.php')
  .then((response) => response.json())
  .then((responseJson) => {
      this.setState({
        dataSource: responseJson
      };
     })
   .catch((error) => {
       console.error(error);
   });

Any help would be appreciated. Thank you!

Answer №1

Utilizing the methods Object.keys and Array.map, we can structure the data to match your desired format.

let data = [
  {
    "18": {
      "sellingUnitName": "unité(s)",
      "qualifier": "GOOD",
      "sizeQualifierName": "gr.20"
    },
    "19": {
      "sellingUnitName": "unité(s)",
      "qualifier": "BAD",
      "sizeQualifierName": "gr.18-20"
    }
  }
];

let dataObj = data[0];

let dataArray = Object.keys(dataObj).map(key => {
  let obj = dataObj[key];
  obj.keyName = key;
  return obj;
})

console.log(dataArray)

Once completed, the dataArray will be structured as

[{keyName: 18, sizeQualifierName: "gr.20", ...}, {keyName: 19, sizeQualifierName:"gr.18-20", ...}]

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

Unexpected behavior encountered in Rails app with unobtrusive JavaScript

I'm facing an issue with my link_to setup. Here's what I have: <%= link_to "Load More", comments_feed_path(@post.id), :id => 'my-link', :remote => true %> In my application.js file, I have the following code: $( document ...

Incorporate communication between the front-end and backend

I encountered an error while attempting to import the getUser function in my backend code. The actual function is located in the frontend at ../utils/auth. How can I successfully import between front-end and backend? Or might there be another issue at pla ...

positioning newly generated dropped elements within the DOM structure dynamically

Hello everyone, I have a query related to drag and drop functionality. I am currently working on an application that allows users to create websites using only drag and drop features. I am facing a challenge in implementing a feature where users can drop e ...

creating dynamic parameterized URLs in Laravel

For example: Here are a few names. - Mujib - Amjed - Anees When someone clicks on "Mujib," the URL should remain the same and only the parameter should change. When someone clicks on "Amjed," the URL parameter should change to . ...

Retrieving user and groups information using Express.js and Node.js with OKTA

Is anyone else experiencing an issue with retrieving user info and group info using the OKTA API? The responses are being sent as strings, requiring me to use JSON.parse() before I can work with the data. Has anyone found a solution to this problem? ...

Encountered a type error while attempting to render and define table columns within a material table component in

Hey there! I'm currently using the Material table to create a table view, and here are the columns that I have defined: const columns: TableColumn[] = [ { title: 'TYPE', field: 'type_of_action', highligh ...

Next.js 13 React Server Component not displaying updated data upon build completion

I have a React Server Component that retrieves its data at build time and does not reload it while the site is running. I expected it to fetch the data once when the server component is first rendered. Is there a way to force this server component to relo ...

Delay in only a portion of the AJAX response

I created a chat application that is functioning correctly, but I am encountering an unexpected behavior. When a user sends a message, the user's name, time, and message should be displayed in order. However, currently, it seems like the username and ...

Show SVG in its ViewBox dimensions

Currently, I am utilizing the img-Tag to showcase SVG images that have been uploaded by users onto my Amazon S3 storage. <img src="http://testbucket.s3.amazonaws.com/mysvg.svg" /> An issue arises once the image is displayed as it does not retain i ...

Fetching SFTP directory listings asynchronously using Node.js

I'm currently working on fetching SFTP listings using Node.js from multiple servers. To achieve this, I am utilizing the ssh2-sftp-client library and trying to manage the asynchronous connections by implementing a customized Promise.all() approach. T ...

Best practice in TypeScript for handling an Enum with a switch-case to assign a variable

Here's an issue I'm facing: I have a variable called Difficulty that is an Enum. Within a function, I need to set the configuration DifficultyConfig based on the value of Difficulty. The current solution I have in mind seems overly complicated: ...

Is there a way to verify if all the values in an array of objects are identical?

In this scenario, my array consists of entries with identical address IDs but different phone types and numbers. I am in need of assistance with iterating through the array to extract the phone type and number when the address ID matches. I seem to encount ...

The React-Leaflet curly braces positioned on the top left corner of the map

Is there a way to remove the curly braces and symbols near the zoom pane when the map is too far? https://i.stack.imgur.com/eGQCd.png p.s. Here is some provided code for reference: p.s. 2 - I have noticed that adding a condition like {condition1 &a ...

Discontinuing the mobx autorun feature upon componentWillUnmount

In my componentDidMount, I have the following autorun function: componentDidMount() { this.autoUpdate = autorun(() => { this.setState({ rows: generateRows(this.props.data) }) }) } Unfortunate ...

What methods are available for managing model fields within a for loop in Django?

As a newcomer to Django, I am embarking on the journey of creating a Quiz web application that presents one question at a time. Upon selecting an answer using radio buttons, the application should promptly display whether the response is correct or incorre ...

What steps can I take to ensure the reset button in JavaScript functions properly?

Look at this code snippet: let animalSound = document.getElementById("animalSound"); Reset button functionality: let resetButton = document.querySelector("#reset"); When the reset button is clicked, my console displays null: resetButton.addEvent ...

The Angular JS field will only be considered valid if its value is more than zero

I have a text box in my form that changes its value dynamically when a user selects a category from a dropdown menu. Initially, the value is set to 0. $scope.validCats = "0"; HTML: <input ng-model="validCats" value="" type="text" class="form-control ...

Utilizing cheerio to set outerHTML in HTML

Could someone kindly assist me with setting the outerHTML of an element using cheerio? I seem to be encountering some issues with this process. For example, let's consider the following HTML structure: <div class="page-info"> <s ...

Unable to include the variable "$localStorage"

While working on my method in app.js, I encountered the following error: Uncaught Error: [$injector:strictdi] function($rootScope, $q, $localStorage, $location) is not using explicit annotation and cannot be invoked in strict mode http://errors.angula ...

Tips on extracting variables from JMeter Selenium WebDriver

Currently, I am dealing with a token that is being returned in the body of a web page. WDS.browser.findElement(org.openqa.selenium.By.xpath("//*[contains(@name,'RequestVerificationToken')]")).getText(); This token is what I need to extract: ...