Home > Back-end >  Nested JSON array displaying as [Object Object] in TextField
Nested JSON array displaying as [Object Object] in TextField

Time:05-05

I have two sets of JSON, Set 1 and Set 2. Set 1 (sizingData) being mapped to textFields like this:

const fillTextField = () => {
    let result = [];
    var keys = Object.keys(sizingHistory);
    keys.forEach(function (key) {
        result.push(sizingHistory[key]);
    });
    return( 
        {result?.map((data) => {
            return ( <TextField variant="outlined" value={data} /> );
        })}
    )
}

I want to map Set 2 (sizingHistory) similarly, but I am getting [Object Object] in the textField rather than the SizingId & SizingComments. This is my attempt at mapping sizinhHistory:

const [sizingHistory, setSizingHistory] = useState("");
const fillHistoryTextField = () => {
    let result = [];
    var keys = Object.keys(sizingHistory["sizinghistory"]);
    keys.forEach(function (key) {
        result.push(sizingHistory["sizinghistory"][key]);
    });
    return (
        {result?.map((data) => {
            return ( <TextField variant="outlined" value={data} /> );
        })}
    )
}

Set 1

{
    "SizingId": 20448,
    "SizingComments": "This is a comment",
}

Set 2

{
    "sizinghistory" : [
        "SizingId" : 20448,
        "SizingComments": "Old Comment",
    ]
}

The fetch function for both sizingData & sizingHistory are called in their own handleOpen functions. UseEffect cannot be used in this case as data is only displayed when a user selects a row in a table containing a SizingId.

CodePudding user response:

You have [Object object] as JS is converting an object to string on Set2, this happens because data.seizingHistory is an array and you have to iterate through it then through the keys of the object inside to get all the data on the text inputs.

This should get you what you need

const [sizingHistory, setSizingHistory] = useState("");
const fillHistoryTextField = () => {
    let result = [];

    (sizingHistory["sizinghistory"]).forEach(element => {
      const keys = Object.keys(element);
      keys.forEach(function (key) {
          result.push(element[key]);
      });
    });

    return (
        {result?.map((data) => {
            return ( <TextField variant="outlined" value={data} /> );
        })}
    )
}
  • Related