首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >嵌套数组中的javascript find()

嵌套数组中的javascript find()
EN

Stack Overflow用户
提问于 2021-06-22 06:13:43
回答 3查看 124关注 0票数 0

我正在尝试用REACT建立一个网站。在主页上有两个按钮,欧洲和美国。假设您单击了“欧洲”。然后你会看到欧洲所有国家的列表。当你点击一个国家时,你应该会看到这个国家的城市列表。

问题是,我如何访问“城市”中的项目?

代码语言:javascript
运行
复制
       const DATA = [
       {
        id: 1,
        title: "EUROPE",
        countries: [
            {
                id: 1,
                country: "france",
                cities: [
                    {
                        id: 1,
                        city: "paris"
                        
                    },
                    {
                        id: 2,
                        city: "toulouse"
                     
                    }
        ];

         // so at homepage, you click "europe", and on the second page i got this:

         const StateCard = () => {
         const { title } = useParams();
         const selectedData = DATA.find( d => d.title === title);
         
         return(
         <div className="main">

         {selectedData &&
          selectedData.countries.map((item, id) => {

          return (
          <div className="card-container" >
           <Link key={id} to={`${title}/${item.country}`}> {item.country} </Link>
           </div>
       );
     })}
  </div>

useParams给我们返回了第一次点击后添加到网址的标题,即“欧洲”。selectedData返回了“EUROPE”中的项:{id: 1,title:"EUROPE",countries: Array(1)}

现在屏幕上显示“法国”。你点击了法国,现在我想显示里面的两个城市。我得到的只有:

代码语言:javascript
运行
复制
const { country } = useParams();

这给了我们“法兰西”。但是我不知道如何进入里面的城市。我试着使用DATA.countries.find(),但是我放在DATA之后的任何东西。给我"TypeError:无法读取未定义的属性'find‘“。

对不起,太长了,谢谢你们!

EN

Stack Overflow用户

发布于 2021-06-22 06:30:29

你可以先找到Country,然后在countriesResult上找到citiesResult,然后再从citiesResult.cities找到城市。

您将收到错误**TypeError: Cannot read property 'find' of undefined**,因为

您正在做的是DATA.countries.find()Data是一个数组,所以你不能对它使用.countries。您必须使用find或索引来查找国家/地区。

代码语言:javascript
运行
复制
const DATA = [{
  id: 1,
  title: "EUROPE",
  countries: [{
    id: 1,
    country: "france",
    cities: [{
        id: 1,
        city: "paris",
      },
      {
        id: 2,
        city: "toulouse",
      },
    ],
  }, ],
}, ];
const title = "EUROPE";
const country = "france";

const countriesResult = DATA.find((d) => d.title === title);
const citiesResult = countriesResult.countries.find(
  (c) => c.country === country
);

const result = citiesResult.cities.map((c) => c.city);

console.log(result);

票数 1
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68075339

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档