0

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

2 Answers 2

3

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)

Sign up to request clarification or add additional context in comments.

2 Comments

how can i get only first value ? instead of all
If you only want the first value there is no need to use map or iterate in the first place. Just use data[0]['First Row'].info
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.