Rohit Verma
Rohit Verma

Reputation: 3785

How to run nested React map function?

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>
                      </>;
                    })
                  )
                : ""}

Upvotes: 0

Views: 40

Answers (2)

niranjan94
niranjan94

Reputation: 826

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>
  );
};

Upvotes: 1

0stone0
0stone0

Reputation: 43983

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)

Upvotes: 3

Related Questions