简体   繁体   English

如何遍历主要 object 内的对象内的数组

[英]How to iterate through array inside objects which is inside main object

I have an API: https://www.gov.uk/bank-holidays.json我有一个 API: https://www.gov.uk/bank-holidays.json

It contains an object, which contains 3 keys (Division) whose value is also an object and it includes an array showing holiday Details (events).它包含一个 object,其中包含 3 个键(Division),其值也是 object,它包含一个显示假日详细信息(事件)的数组。 I want to print the "title" and 'date' from it for each Division.我想为每个部门打印“标题”和“日期”。 Below is the code.下面是代码。 How to render the data for title and date inside the Holiday.js?如何在 Holiday.js 中呈现标题和日期的数据?

     export default function App() {
  const [data, setData] = useState([]);

  const fetApi = () => {
    fetch("https://www.gov.uk/bank-holidays.json")
      .then((res) => res.json())
      .then((items) => setData(items));
  };

  useEffect(() => {
    fetApi();
  }, []);

  return (
    <div className="App">
      <Holidays data={Object.entries(data)} />
    </div>
  );
}

/ / Holiday.js

const Holidays = ({ data }) => {
  // console.log(data);
  return (
    <div>
      <ol>
        {data.map((item, i) => {
          return (
            <li key= {i}>
              <div>title:</div>    //render title here
               <div>Date :</div>    //render date here
           </li>
          );
        })}
      </ol>
    </div>
  );
};

this is Sandbox link: enter link description here这是沙盒链接:在此处输入链接描述

Change Holliday Element into: (explanation on comments)将 Holliday 元素更改为:(评论说明)

const Holidays = ({ data }) => {
  // console.log(data);
  return (
    <div>
      <ol className="App">
        {data.map((item, i) => {
          // since you are passing Object.entries, the first parameter is the key
          // and the second one are the values
          const [key, obj] = item;

          // you then just have to map the event inside the values
          return obj.events.map((o, index) => (
            <li key={index}>
              <div>title: {o.title}</div>
              <div>Date : {(o.date)}</div>
            </li>
          ));
        })}
      </ol>
    </div>
  );
};

replace your Holiday comonent with this用这个替换你的假期

const Holidays = ({ data }) => {
  const ListItem = (array) => {
    console.log(array);
    return array[1].events.map((item, i) => {
      return (
        <li key={i}>
          <div>title: {item.title}</div>
          <div>Date :{item.date}</div>
        </li>
      );
    });
  };
  return (
    <div>
      <ol>{data.map((array) => ListItem(array))}</ol>
    </div>
  );
};

export default Holidays;

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

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