简体   繁体   English

访问也是数组 {React, Javascript} 的属性返回未定义

[英]Accessing a property that is also an Array {React, Javascript} returns undefined

This might looks stupid, but i'm lost.这可能看起来很愚蠢,但我迷路了。 I want to Map through countries and regions array.我想通过国家和地区数组映射。 I have a Countries Array that also includes Region's Array .我有一个Countries Array ,其中还包括Region's Array I can access the Countries Array, but when i try to access the Regions Array i returned from the Countries Array , it returns undefined.我可以访问国家数组,但是当我尝试访问从Countries Array返回的Regions Array Countries Array ,它返回未定义。 Here is a minimal example.这是一个最小的例子。

Full code on CodeSandBoxCodeSandBox 上的完整代码

 const Countries = [ { countryName: "Afghanistan", countryShortCode: "AF", regions: [ { name: "Badakhshan", shortCode: "BDS", }, { name: "Badghis", shortCode: "BDG", }, { name: "Helmand", shortCode: "HEL", }, { name: "Herat", shortCode: "HER", }, { name: "Jowzjan", shortCode: "JOW", }, { name: "Kabul", shortCode: "KAB", }, { name: "Kandahar", shortCode: "KAN", } ], }, { countryName: "Åland Islands", countryShortCode: "AX", regions: [ { name: "Brändö", shortCode: "BR", }, { name: "Eckerö", shortCode: "EC", }, { name: "Sund", shortCode: "SD", }, { name: "Vårdö", shortCode: "VR", }, ], } ] const mappedCountries = Countries.map(({ regions }) => regions); const mappedRegion = mappedCountries.map(({ name }) => name); console.log(mappedCountries); console.log(mappedRegion);

you are returing an array in the map method.您正在 map 方法中返回一个数组。 so the result is an array of arrays.所以结果是一个数组数组。

you need to flatten your result.你需要flatten你的结果。 an easy alternative would be using reduce一个简单的替代方法是使用reduce

const mappedCountries = Countries.reduce((memo, { regions }) => [...memo, ...regions], []);
const mappedRegion = mappedCountries.map(({ name }) => name);

您可以像这样更改第二张地图内的条件以访问区域名称 - mappedCountries.map(e => e.map(({name}) => name))

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

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