Home > OS >  How to run nested React map function?
How to run nested React map function?

Time:12-10

I have a JSON I need to fetch data & display in UI but not able to do due to nested.

JSON data:

data =[
  {
        "First Row": {
            "info": 274.176,
        }
    },
    {
        "Second Row": {
            "info": 139.536,
        }
    }
]

My Code:

{data
                ? data.map((val, i) =>
                    val[i].map((val2) => {
                      <>
                        <div>{val2.info}</div>
                      </>;
                    })
                  )
                : ""}

CodePudding user response:

Use Object.values() to get an array of all the values, then use [0] to get the first object where you can acces the info as desired:

data.map((val, i) => Object.values(val)[0].info)
[
  274.176,
  139.536
]

const data = [
    { "First Row": { "info": 274.176, } },
    { "Second Row": { "info": 139.536, } }
];

const r = data.map((val, i) => Object.values(val)[0].info);
console.log(r)

CodePudding user response:

If you want to display only the info value, you can do the following. It loops through the data array. And for each item, gets the value of the first key. (assuming each item only has one key)

const DataDisplay = ({ data }) => {
  return (
    <div>
      {data.map((item, index) => {
        return (
          <div key={index}>
            <h3>{Object.keys(item)[0]}</h3>
            <div>{Object.values(item)[0].info}</div>
          </div>
        );
      })}
    </div>
  );
};
  • Related