Extracting the name from a JSON key/value pair and then adding it to a TextField

Here is a sample JSON data:

{
  "Id": 1,
  "Title": "Information on Jane Smith",
  "Comments": "Additional details here",
  "UpdatedBy": "Jane Smith",
  "UpdateDate": "May 25 2022 3:45PM"
}

I am looking to convert this JSON into MUI TextFields, with the label names as TextField labels and their corresponding values as TextField values. The ability to edit the values is also required.

Below is an example of how I'm handling my array of data:

const [specificDetails, setSpecificDetails] = useState("");
const fetchDetailsData = async (record_id, detail_id) => {
  setSpecificDetails(
    await fetch(`/api/years/YR2023/records/${params.id}/details/questions`).then((response) =>
                response.json()
            )
  );
};

These are the instances of Text Fields being utilized in this scenario:

<TextField
  value={}
  label={}
/>

Answer №1

If the variable singleSizing is not a JSON object, make sure to run it through a mapping function first:

Utilize the method Object.entries to break down the object into key/value pairs and then use .map() to iterate over each entry and create components accordingly.

// ...

  return Object.entries(singleSizing).map(sizingEntry => {
      const [label, value] = sizingEntry; // Example: ['Title', 'Details about John Smith']
      
      return <TextField label={label} value={value} />
  });

// ...

If you need to modify the values, explore MUI form components or another form library and consider adjusting the structure of the state for easier updates.

Answer №2

If you're looking to iterate through an object and display its key-value pairs, consider using the combination of .map and Object.keys.

{
     
      
    Object.keys(myObject).map(key => (
      <TextField 
        value = {
          myObject[key]
        }
        label = {
          key
        }
       />
    ))
      
   }
  

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

When attempting to use Ajax, the operation fails; however, if I directly access the URL,

When using firebug, I attempted to make the following AJAX call: var rootUrl = 'http://172.24.105.22:8080/geoserver/Chennai_Sub/ows'; var defaultParameters = { service: 'WFS', version: '1.0.0', request: 'Get ...

Leveraging R's Plumber library, develop a GET endpoint for serving CSV-formatted data instead of JSON

While I find this to be a great demonstration of R's plumber library overall, my main challenge lies in serving data in a csv format. My current project involves using R's plumber package to create an API endpoint for sports data. Specifically, ...

What is the best way to divide a string into an array containing both linked and non-linked elements?

I'm struggling to find the right solution to my problem. I need to create a view that is enclosed in a clickable div. The content will consist of plain text mixed with clickable URLs - the issue arises when clicking on a link also triggers the method ...

Can Eloquent Model JSON Method Include Null Values?

Is there a way to print a Laravel Eloquent Model with null values? I am looking to generate a new Question object that includes all fields, but with null values. However, when I attempt this, it only prints an empty array, []. var app = new Vue({ el: ...

Adjust the size of a textarea once text is removed

When you type text, a textarea expands in size. But what if you want it to dynamically decrease its height when deleting text? $('textarea').on('input', function() { var scrollHeight = parseInt($(this).prop('scrollHeight&apos ...

The browser failed to display the SVG image, and the console log indicated that the promise was rejected, with the message "false."

I'm struggling to understand why my SVG isn't showing up on the screen. The console log is displaying "false," which I believe indicates that a promise was rejected Here is the TypeScript file I am working with: export class PieChartComponent im ...

Iterate through the collection to retrieve the value associated with a specific key

In the JSON response I have received, I am trying to extract the value of "fees" corresponding to "detailComponent" with the identifier "FULL_FEE". However, instead of retrieving the desired value, the loop seems to be fetching the last value associated wi ...

Proper method for extracting and sending the final row of information from Google Sheets

The script I have is successfully formatting and sending out the information, but there is an issue. Instead of sending only the latest data, it is sending out each row as a separate email. I specifically want only the last row of data to be sent. functio ...

What should be done if an image is not wide enough to stretch it to match the width of the window?

When the image is not full screen, it looks fine but when it's viewed in full screen, there's a white area on the right side which is likely due to the image not being large enough. Is there a way to automatically stretch the image so that its wi ...

When using async functions in iterative processes

In my current setup, I am utilizing a for-each loop to handle a list and specifically require element n to be processed only after element n-1 has completed: let elements = ["item1", "item2", "item3"]; elements.forEach(function(element){ someAsyncFun ...

Adjust the dimensions of an element using Protractor

When using the getSize method, I am able to determine the size of an element but I am struggling to understand how to change its height. To provide some additional context, my goal is to verify if a user can resize a textarea element. Should I simply adju ...

What benefits do Adobe Creative Cloud apps offer for developing interactive content in AEM?

My client recently transitioned to AEM for their website, and we are tasked with creating an interactive HTML5 'component' to be embedded on a page. While we have previously used custom HTML5 for components, integrating them into pages on the old ...

JavaScript Object DeclarationCreating Objects in JavaScript

In this scenario, I have the following code snippet. Upon calling the constructor, an object is created. When updating the fields, modifications are made as shown below. It's important to note that direct modification of the Comment() function is not ...

Fading colored images and backgrounds using Javascript

Although js and html are not my strong points, I am attempting to create two simple effects on a single page. As the user scrolls down the page, I want the background image or color to change as different divs come into view and then move off the screen. ...

When trying to use bootstrap modal buttons, they do not trigger with just a single click when

In my Angular code, I have implemented validation logic for when $locationChangeStart is fired. When this event occurs, I need to call event.preventDefault() to stop it and display a Bootstrap modal. However, I am encountering an issue where I have to clic ...

Identify user input with Python Selenium for keyboard and mouse interactions

As a frequent user of Selenium Browser for my everyday browsing needs, I am looking to implement some code that will be triggered when certain keys are pressed on any page. Initially, I considered loading JavaScript onto each page to track key and mouse in ...

Ways to determine if two variables point to the same object in javascript

Recently, I started learning JavaScript and came across the spread operator. From what I learned, it deep copies the top-level elements of an array or object but only shallow copies the nested arrays or objects. To visualize this concept in action, I tried ...

Is there a way to automatically dismiss a notify.js notification?

I am currently attempting to forcefully close an opened notification by clicking a button, following the instructions provided in the advanced example of the notify.js API. Can someone please explain how this can be accomplished? function CLOSE() { $( ...

Difference between ng-controller variable and ng-init variable

When working with the code snippet below in angularJS, <script type="text/javascript"> angular.module('app').controller('add', ['$scope',function($scope) { $scope.name = "Bonita Ln"; }]); </script& ...

Using THREE.js to cast rays from a secondary camera onto the scene

I've been attempting to raycast the mouse from my camera in order to trigger hover and click events on meshes within my scene. The issue I'm facing is that my camera is currently a child object of another mesh (to facilitate easier camera moveme ...