gpt4 book ai didi

javascript - 找到每个国家的大陆

转载 作者:数据小太阳 更新时间:2023-10-29 05:59:47 25 4
gpt4 key购买 nike

我有一系列大陆和国家:

const continents = [
{
continent: 'Europe',
countries: [
'Albania',
'Andorra',...
],
},
{
continent: 'Asia',
countries: [
'Afghanistan',
'Bahrain',...
],
},
{
continent: 'Africa',
countries: [
'Algeria',
'Angola',...
],
},
{
continent: 'Americas',
countries: [
'Antigua and Barbuda',
'Bahamas',...
],
},
]

还有一些国家:

const countries = ['Angola', 'Andorra']

我想遍历国家并返回这样的对象数组:

const result = countries.map(country => {
return {
continent: ??,
country: country,
}
})

如何找到每个国家的大陆?

我试试这个:

const continent = continents.forEach((continent, i) => {
const countries = continent.countries
if (find(countries, value.country)) return continent.continent
})

但是我明白了

[ts] Not all code paths return a value. [7030]

最佳答案

您可以通过使用 Array#find 检查值来找到 continentArray#includes

const
continents = [{ continent: 'Europe', countries: ['Albania', 'Andorra'] }, { continent: 'Asia', countries: ['Afghanistan', 'Bahrain'] }, { continent: 'Africa', countries: ['Algeria', 'Angola'] }, { continent: 'Americas', countries: ['Antigua and Barbuda', 'Bahamas'] }],
countries = ['Angola', 'Andorra'],
result = countries.map(country => ({
continent: continents.find(({ countries }) =>
countries.includes(country)).continent,
country,
}));

console.log(result);

关于javascript - 找到每个国家的大陆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54456556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com