简体   繁体   English

如何运行嵌套 React map function?

[英]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 我需要获取数据并在 UI 中显示,但由于嵌套而无法执行。

JSON data: JSON 数据:

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

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:使用Object.values()获取所有值的数组,然后使用[0]获取第一个 object,您可以在其中根据需要访问info

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)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM