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

Is there a way to set the AutoComplete control in Material-UI as mandatory?

Yesterday was a frustrating day as I attempted to set the AutoComplete control as required. Unfortunately, the API lacks a required attribute and onNewRequest doesn't trigger if the textbox is empty. Additionally, onBlur has a glitch preventing it fro ...

Utilizing the HTML button element within an ASP file combined with JavaScript can lead to the reloading of the

I am attempting to create a JavaScript function for an HTML button element. However, I have noticed that it causes the page to reload. Strangely, when I use an input with a button type, everything works perfectly. What could be causing this issue and why a ...

Tips for displaying user data from a mongodb database on a webpage, making edits to the information, and then saving the updated data

I have a website where users can register, log in, and update their profile information. However, I am facing an issue where only the data of the first user in the database table is being retrieved. How can I get the data of the currently logged-in user? ...

Utilize the 'response.download' method to retrieve unique data not typically expected for a given request

Each time I try to download a file, the response I get is different. The file is generated correctly every time: user,first_name,last_name,active,completed_training 4,Foo,Bas,YES,YES 5,Ble,Loco,NO,NO 9,gui2,md,NO,NO 3137,foo,baz,NO,NO However, the respons ...

Click to add a different template into the document

My HTML page consists of a form with multiple input fields and a carousel. Towards the bottom of the form, there is a button labeled Add another quote. This button essentially duplicates the input fields above (all contained within class="quote"). Here&ap ...

The particular division is failing to display in its designated location

This is quite an interesting predicament I am facing! Currently, I am in the process of coding a website and incorporating the three.js flocking birds animation on a specific div labeled 'canvas-div'. My intention is to have this animation displa ...

Custom validation preventing Ng-minlength from functioning correctly

I'm currently working on an angularJS project where I am trying to create a form for users to input their username. The application needs to validate if the username is available in the database and if it falls within a character length of 5 to 10. & ...

Is it possible to incorporate an additional value into the jQuery widget 'Autocomplete' by using a second variable?

For several years, I have been utilizing the jQuery 'Autocomplete Widget' in my projects. This plugin allows me to pass a value labeled as 'term' to the PHP SQL code that works like this: $( "#cs1" ).autocomplete({ aut ...

hover over the picture with your cursor

Struggling with jquery and css, could use some assistance :) Check out my html code below: <html> <head> //myscripts <script> $(document).ready(function(){ $(".cover").hover(function(){ //the function i need to write } ...

Utilize angularjs daterangepicker to refine and sift through data

I am currently utilizing the ng-bs-daterangepicker plugin by ng-bs-daterangepicker and encountering difficulty in filtering when selecting a start date and end date. Below is a snippet of my code: <input type="daterange" ng-model="dates" ranges="range ...

Difficulty in toggling the visibility of the react-date-range picker package when selecting a date

I need assistance with a problem I'm facing. I am having trouble hiding and showing the react-date-range picker upon date selection. The issue is related to a package that I am using for date range selection. You can find the package link here - https ...

Executing a function upon loading a page triggered by a submitted form

Recently on my index.php page, I implemented a form that posts data into a third-party newsletter system. After the form submission, the page reloads to index.php?mail&. Is there a way to detect when the page is loaded and determine if the form has bee ...

Using Webpack postcss prefixer with Vue CLI 3

As I work on implementing Bulma CSS in my project using Vue CLI 3, I encounter the need to prefix the classes with webpack. While I found an example of this process, adapting it from a webpack config to vue.config.js poses some challenges. Here is the ini ...

Exploring Recursive JSON Parsing in C#

I have thoroughly reviewed all the recursive JSON sections available here, and none of them appear to be truly recursive. Nonetheless, I am faced with a challenge. How can I efficiently iterate through all the departments in this JSON file? The depth of th ...

Ways to convert a string into an object on Android using deserialization techniques

Need help with deserializing the following string in an Android application. I have attempted the following: String json= ls.get(j).getCwc(); Example example = new Gson().fromJson(json, Example.class); Json [{ "company":"gjjzh", "AvgSal":"hjsj" }, { ...

Is it possible to retrieve the createdAt timestamp without displaying the 'GMT+0000 (Coordinated Universal Time)'?

After conducting an extensive search, I have yet to find a satisfactory answer. My goal is to configure it without including the CUT time. {name: "Registered:", value: `${user.createdAt}`}, {name: "Joined:", value: `${message.guild.joinedAt}`} Presently, ...

Within the HTMLDivElement.drop, the parent element now encapsulates the new child element

I've encountered a DOM exception that has me stuck. My issue involves div elements and a button - when the user clicks the button, a random div is selected and another div with a background-color class is appended to it. Essentially, clicking the butt ...

How can I turn off autocomplete in MUI textfields?

Currently, I am working with the latest version of mui. Within my user contact info form, there is a zip code field that I do not want to be auto completed if the value is null. However, despite my efforts, it continues to autocomplete with the email saved ...

A JavaScript or CSS file within an HTML document

I understand this may seem like a silly question. However, out of curiosity, is there a way to upload an HTML file (with a .html extension) as a JavaScript or CSS file (renamed with a .js or .css extension), specifying the type header as either HTML or js ...

Unleashing the Power of v-model in Vue.js: A Comprehensive Guide to Referencing Input

I am a beginner in vue.js and I am currently facing an issue with making a get request from a field that has a v-model="embed.url" after pasting a link. The paste event works fine, but I'm struggling to reference the input with v-model="embed.url" and ...