What is the best way to construct a JSON object for React based on the data from a JSON API response?

My API will be sending back data in the following format:

[  
   {  
      "id":5,
      "name":"Example",
   },
   {  
      "id":634,
      "name":"Test",
   },
   ...
]

In my React application, I need to create a JSON object like this:

const fields = [
  {
    title: 'Example',
    type: 'select',
    choices: [
      {},
      { label: '1', value: '1' },
      { label: '2', value: '2' },
    ],
  },
  {
    title: 'Test',
    type: 'select',
    choices: [
      {},
      { label: '1', value: '1' },
      { label: '2', value: '2' },
    ],
  },
  ...
]

The options will stay the same and are not based on the server response.

Is there a way to dynamically generate this JSON object depending on the API results?

Update

var origArray = [ {id:1, name: "aaa"},
                  {id:2, name: "bbb"},
                  {id:3, name: "ccc"},
                  {id:4, name: "ddd"}];

const fieldoptions = {
  type: 'select',
  choices: [
    {},
    { label: '1', value: '1' },
    { label: '2', value: '2' },
  ]
};

const fields = origArray.map(item => ({
 title: item.name,
 fieldoptions
}));

console.log('fields');
console.log(fields)

The issue is that there is a parent element of fieldoptions that should not appear in the output.

(4) [Object, Object, Object, Object] 0 : Object fieldoptions : Object title : "execution"

Answer №1

To manipulate your array, utilize the .map() method to apply a function to each element within it.

The provided function will modify your data by incorporating additional fields or making transformations as needed.

const newFields = {
  type: 'checkbox',
  options: [
    {},
    { label: 'A', value: 'A' },
    { label: 'B', value: 'B' },
  ]
};

const updatedData = data.map(item => ({
 title: item.name,
 ...newFields
}));

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

Issue with Angular binding not updating after being assigned in promise.then() function

Within my angular application, I have a $scope variable labeled as user which contains a name property. Whenever I click on a link to set this user variable to "test": <a href="#" ng-click="setUser()">Set User</a> Using the following functio ...

Spring REST service prevents Cross-Origin Requests with AJAX

Having Trouble Accessing Spring REST Service My spring service @RequestMapping(value = "/MAS/authenticate", method = RequestMethod.POST) public ResponseEntity<Map<String, String>> authenticate(@RequestBody Subject subject) { Map<String ...

Checkbox does not trigger onCheck event

I am facing an issue with a checkbox component from material-ui where the onCheck event is not firing. <Checkbox label="label" onCheck={onCheck} checked={currentDocument.ispublic} /> function onCheck() { currentDocument.ispublic = !current ...

Choosing the open status of an HTML list

Is there a way to determine which containers in a list are currently open and which ones are still closed? Currently, I am utilizing the slideDown(), slideDown(), and addClass functions on divs with the specific class="section_hdl_aktiv". However, I want ...

The jQuery message validator is currently experiencing some issues with its functionality

I am working on implementing a basic login system using jQuery and it appears to be functioning correctly, but I keep getting an error message in my jQuery code here: alert('Error in system');. What's puzzling is that when I use alert(answe ...

Using jQuery AJAX to send data containing symbols

When making an AJAX call, I am including multiple values in the data like this: var postData = "aid="+aid+"&lid="+lid+"&token="+token+"&count="+count+"&license="+license; postData = postData + "&category="+category+"&event_name="+e ...

When sending strings through an ajax call, spaces are getting converted to "'+'"

In my attempt to utilize AJAX for sending a POST request with multiple strings as parameters, I encountered an issue. The strings I am sending sometimes contain spaces. However, upon receiving the POST on the C# server side, I noticed that the string com ...

What is the best way to arrange elements based on the numeric value of a data attribute?

Is there a way to arrange elements with the attribute data-percentage in ascending order, with the lowest value first, using JavaScript or jQuery? HTML: <div class="testWrapper"> <div class="test" data-percentage="30&qu ...

Accessing the current clicked item in $scope using an Angular Directive within ng-repeat

I have set up a custom directive called calendar which includes a date picker created in JQuery. To associate the ng-model with the date picker, I am using the following code successfully: var clickedID = "#" + $scope.indexid + "_datePicker"; $(clickedID ...

“Rails encountering issues with proper parsing of QPX Express API object”

I've been struggling for a while now to understand why my JSON object isn't working properly when passed through AJAX to Rails using Typhoeus. I apologize if this seems like a beginner question, as I'm fairly new to web development. Despite ...

Exploring LZMA compression in conjunction with next.js

Is anyone familiar with using the lzma algorithm to compress video, photo, text, etc. in the Next.js framework? I have searched everywhere but couldn't find a solution. I haven't found a proper demonstration or answer anywhere. I would greatly a ...

Ensure that a synchronous action is performed prior to each Backbone HTTP request

For each authenticated request (GET, POST, etc) in my Backbone/Marionette application, it is necessary to include an accessToken. The accessToken and expireDate are stored in the localStorage. To verify if the accessToken has expired, I utilize the metho ...

Backbone.js: Navigating the Default Path Issue

I've embarked on creating my very first BB app. Progress is decent, but I've hit a roadblock. My router implementation appears as follows: var PlayersAppRouter = Backbone.Router.extend({ routes: { '': 'index', ...

leveraging socket.io alongside express router

As someone who is relatively new to node.js, I am currently in the process of creating a webchat application. My project consists of a server.js file and a router.js file where I have defined all my routes. Unlike many others, I am not using express-genera ...

Tips for ensuring form elements do not contain white space before submitting through AJAX

Before sending my form using AJAX request, I want to validate the form elements. Even though it checks for errors, the form still gets submitted. This is my code: $('#accountFormAddEdit').on('submit', function(e){ e.preventDef ...

Perform an ajax POST call to a server using ajax/jQuery techniques

I am attempting to utilize ajax to send a post request to a different domain and receive a json response. The server is located within my company premises and the logs show that it is indeed sending back a json response. Below are two samples of my attemp ...

What is the proper placement for index.html <head/> class helper functions within a ReactJS Component?

My custom helper functions are stored in a JavaScript file called classie.js: ( function( window ) { 'use strict'; function classReg( className ) { return new RegExp("(^|\\s+)" + className + "(\\s+|$)"); } var hasClass, ...

"An ActionResult is received as null when the model is passed as an

Has anyone encountered a situation where the model is null when passed to the controller? I inserted an alert in the ajax call to verify the value and it seemed correct, but upon debugging on the first line of the controller's ActionResult, it shows a ...

The node.js express framework is unable to fetch the URL and data from the node server

Attempting to create a basic application to retrieve data from a nodejs server. But encountering issues with accessing the file in both the browser and POSTMAN. Despite multiple attempts to verify the URLs, I have been unsuccessful. Below are the files i ...

Trigger a function post-rendering in a React component

Hey everyone, hope you're having a great day! I've been diving into React for a few months now. I'm making an effort to steer clear of using the traditional React Components, opting instead for React Hooks. However, there are instances wher ...