Exploring the possibilities of implementing the .map() function on a JSONArray within a ReactJS project using ES

When I receive a JSONArray from the server, my goal is to use .map() on it in order to extract key-value pairs of each object within the array. However, when I try to implement this code, I encounter an error stating "files.map is not a function". Can someone please assist me in resolving this issue?

showUploadedFiles()
  {
    const page = 1;
    const items_per_page = this.state.event.file_ids.length;
    getAllTaskFiles(this.state.event.id, page, items_per_page).then((allFiles) => {
      this.renderUploadedFiles(allFiles);
    });

  }

  renderUploadedFiles(files)
  {
    let details = null;
    details = files.map((singleFile) => {
    return (
      <div>
        <a href="#" >{singleFile.filename}</a> 
        <a href="#" >{singleFile.file_path}</a>
      </div>
      );
    });
  }  

This is my JSONArray:

[{"file_id": 5224879255191552, "filename": "children_walk_friends_forest_116878_3840x2160.jpg", "file_path": "/api/files/encoded_gs_file%3AdHJhY2tpbmctYXBpL3YxL2FjY291bnRzLzU2Mjk0OTk1MzQyMTMxMjAvdGFza3MvNDk5NjE4MDgzNjYxNDE0NC81MjI0ODc5MjU1MTkxNTUyL2Zha2UtemRNeklhZ1RTYl9PN3RXY2pXbkhVQT09"}, {"file_id": 4943404278480896, "filename": "banner_old.jpg", "file_path": "/api/files/encoded_gs_file%3AdHJhY2tpbmctYXBpL3YxL2FjY291bnRzLzU2Mjk0OTk1MzQyMTMxMjAvdGFza3MvNDk5NjE4MDgzNjYxNDE0NC80OTQzNDA0Mjc4NDgwODk2L2Zha2UtcmJjbDBVdVFzVmZkMjRtRUV2ME1xZz09"}] 

Answer №1

It has been noted by fellow users that in order to extract an object from your string, you must use JSON.parse(). Below is the code snippet which demonstrates how to store your files in an array:

const str = '[{"file_id": 5224879255191552, "filename": "children_walk_friends_forest_116878_3840x2160.jpg", "file_path": "/api/files/encoded_gs_file%3AdHJhY2tpbmctYXBpL3YxL2FjY291bnRzLzU2Mjk0OTk1MzQyMTMxMjAvdGFza3MvNDk5NjE4MDgzNjYxNDE0NC81MjI0ODc5MjU1MTkxNTUyL2Zha2UtemRNeklhZ1RTYl9PN3RXY2pXbkhVQT09"}, {"file_id": 4943404278480896, "filename": "banner_old.jpg", "file_path": "/api/files/encoded_gs_file%3AdHJhY2tpbmctYXBpL3YxL2FjY291bnRzLzU2Mjk0OTk1MzQyMTMxMjAvdGFza3MvNDk5NjE4MDgzNjYxNDE0NC80OTQzNDA0Mjc4NDgwODk2L2Zha2UtcmJjbDBVdVFzVmZkMjRtRUV2ME1xZz09"}]';

const files = JSON.parse(str);
const details = files.map((singleFile) => {
  return (
    `<div>
      <a href="#">{singleFile.filename}</a> 
      <a href="#">{singleFile.file_path}</a>
    </div>`
  );
});

console.log(details);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

The command "actions" in Selenium is not recognized

I am having trouble trying to perform a mouse click based on position. No matter what I try, I keep receiving the same error message. I encountered this issue when attempting a double click on the main search bar of google.com. For assistance, refer to: ...

Exploring the location.path in angularjs

Is there a way to use $location.path for redirection in angularjs? I have the configuration below: ngModule.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) { $urlRouterProvider. ...

Issues encountered when trying to modify the Content-Type of POST requests using ngResource versions 1.0.6 and 1.1.4

Despite numerous attempts and trying various solutions found online, I am still unable to solve this issue. Similar questions have been asked in the following places: How to specify headers parameter for custom Angular $resource action How can I post da ...

Creating a dynamic table in AngularJS that can add rows and columns with cyclic values

Seeking assistance for a programming challenge. I have created a form with 2 input fields for specifying the dimensions of a table (number of rows and columns), along with a button. When this button is clicked, the table should be dynamically populated wit ...

Tips on how to deactivate the Material UI DataGrid's next page button during API loading

This snippet pertains to the Material UI Datagrid component. In order to prevent users from moving to the next page while the API is still loading, I need to disable the Go to next page button. <DataGrid autoHeight getRowHeight={getRow ...

How can you store JavaScript objects to files, including their methods, in a Node.js environment?

In reading about saving objects to files in Node.js here on Stack Overflow, I understand the process. However, I am curious if there is a method that allows for writing an object in a manner that would enable me to reload the object into memory along wit ...

JS: Issue with iterating over objects

Within my JavaScript code, there exists an object named box_object with the following structure: ({ id:"3", text:"this is a box object", connection_parent:["1", "2"], connection_child:["5", "6"], connectiondata_child:{ 0:{id:"5", ...

I'm having trouble getting my search program to function properly with React

I have recently started learning React and I am currently working on a basic program that searches the GitHub API to retrieve repository names and URLs. Unfortunately, I'm experiencing some issues with getting it to function properly. In a previous ve ...

What is the best way to implement vuelidate when dealing with an array of objects?

In my form questionnaire, I am looping through an array of objects. Each object has five properties, but only one property needs validation. The validation setup in the component looks like this: specificGifts: { $each: { passThrough: { ...

Error 405: Javascript page redirection leads to Method Not Allowed issue

After receiving the result from the ajax success method, I am facing an issue where the redirection to another page is being blocked and displaying the following error: Page 405 Method Not Allowed I am seeking suggestions on how to fix this as I need to ...

Make the textarea larger and bring it to the forefront when it is selected

I would like to make a textarea expand (increase its height) when it is in focus. The expanded textarea should not push the content down, but rather be displayed above other content. Currently, this is the code I am using (check out the example here): $( ...

Bringing in d3js into Angular 2

Is there a way to successfully import d3js into an Angular2 project? I have already installed d3js using npm and added it to my systemJs, but am encountering a traceur.js error. I also attempted to just use the latest cdn in a script tag and tried import * ...

Error 34 on Twitter: "Apologies, but the requested page cannot be found" at: twitter.com/statuses/user_timeline/flecpoint.json?count=25

Some time ago, I developed a basic PHP script that reads Twitter status messages. It utilizes the twitter json feed found at https://twitter.com/statuses/user_timeline/flecpoint.json?count=25. The script fetches the timeline, stores it in a cache, and peri ...

Comparing json_encode and var_dump for mysqli connection outputs

Our $link variable consists of the following: $link = mysqli_connect('localhost', 'user', 'pass', 'db'); When we use var_dump($link);, it shows the correct values for keys: ["affected_rows"]=> int(0) ["client_ ...

Guide on submitting a form through the Angular 2 HTTP post method with JavaScript

Currently working on grasping the concepts of Angular2, but facing challenges when attempting to utilize http.post() for submitting a form to my Web API. ...

Utilizing a switch statement in Jquery to target specific input elements for focus

My Objective As a user presses enter, I want to target specific input elements with a data-index attribute value between 0-2 and of type text. Then, I plan to check their attribute values using a switch statement to perform certain actions. Presented bel ...

Converting MySQL data to JSON format with PHP and utilizing the GROUP_CONCAT function

I've been trying to convert my home temperature table into JSON format. While I have successfully achieved this for one location using WHERE, I'm struggling to get the code right in order to group it by location, as demonstrated below. I am work ...

I've noticed that every time I use the simple-encryptor npm to encrypt something, the output is always different

Can you assist me in solving this issue? var key = 'real secret keys should be long and random'; // Generating an encryptor: var encryptor = require('simple-encryptor')(key); var encryptedText = encryptor.encrypt('testing') ...

Running a Blitz.js api handler triggers a Google Cloud Storage call failure with the message "error:0909006C:PEM routines:get_name:no start line"

When attempting to utilize @google-cloud/storage within a Blitz.js /api handler, I encounter the following error: error:0909006C:PEM routines:get_name:no start line at Sign.sign (internal/crypto/sig.js:110:29) at NodeCrypto.sign (C:\Users&bsol ...

I'm having some trouble with my middleware test in Jest - what could be going wrong?

Below is the middleware function that needs testing: export default function validateReqBodyMiddleware(req: Request, res: Response, next: NextFunction) { const { name, email }: RequestBody = req.body; let errors: iError[] = []; if (!validator.isEmai ...