gpt4 book ai didi

javascript - .join() 函数在 map 函数中无法正常工作

转载 作者:行者123 更新时间:2023-12-02 22:43:50 24 4
gpt4 key购买 nike

我正在尝试使用映射函数将对象遍历为以下格式:

Name: Hong Kong
TopLevelDomain: .hk
Alpha2Code: HK
Alpha3Code: HKG
CallingCodes: 852
Capital: City of Victoria
AltSpellings: HK, 香港
Region: Asia
Subregion: Eastern Asia
Population: 7324300
Latlng: 22.25, 114.16666666

来自下面的 JavaScript 对象:

const object = {
"name": "Hong Kong",
"topLevelDomain": [
".hk"
],
"alpha2Code": "HK",
"alpha3Code": "HKG",
"callingCodes": [
"852"
],
"capital": "City of Victoria",
"altSpellings": [
"HK",
"香港"
],
"region": "Asia",
"subregion": "Eastern Asia",
"population": 7324300,
"latlng": [
22.25,
114.16666666
],
"demonym": "Chinese",
"area": 1104.0,
"gini": 53.3,
"timezones": [
"UTC+08:00"
],
"borders": [
"CHN"
],
"nativeName": "香港",
"numericCode": "344",
"currencies": [
{
"code": "HKD",
"name": "Hong Kong dollar",
"symbol": "$"
}
]
};

我的尝试是:

const object = { "name": "Hong Kong", "topLevelDomain": [ ".hk" ], "alpha2Code": "HK", "alpha3Code": "HKG", "callingCodes": [ "852" ], "capital": "City of Victoria", "altSpellings": [ "HK", "香港" ], "region": "Asia", "subregion": "Eastern Asia", "population": 7324300, "latlng": [ 22.25, 114.16666666 ], "demonym": "Chinese", "area": 1104.0, "gini": 53.3, "timezones": [ "UTC+08:00" ], "borders": [ "CHN" ], "nativeName": "香港", "numericCode": "344", "currencies": [ { "code": "HKD", "name": "Hong Kong dollar", "symbol": "$" } ] };
let display = [];
let print = Object.keys(object).map(function(elem){
if(object[elem] == 0 || object[elem] ==""){
display = "N/A";
} else if (typeof object[elem] =='object'){
display = object[elem].join(", ") ;
} else {
display = object[elem];
}
return `${elem.charAt(0).toUpperCase()}${elem.slice(1)}: ${display}`;
})
console.log(print.join('\n'));

然而,出现了一个错误,我不知道如何处理它。据我所知 .join() 可用于连接数组的元素。有什么想法吗?

TypeError: object[elem].join is not a function

最佳答案

因为您有嵌套对象。object[elem].join 不起作用 join 是一个数组函数,它只适用于数组。就像下面这样

"currencies": [
{
"code": "HKD",
"name": "Hong Kong dollar",
"symbol": "$"
}
]

对于数组,您还需要一个 if,并且当存在嵌套对象时,需要使用递归函数

function print(object) {
let objMap= Object.keys(object).map(function(elem){
if(object[elem] == 0 || object[elem] ==""){
display = "N/A";
} else if (object[elem].constructor === Array){
display = object[elem].join(", ") ;
} else if (typeof object[elem] =='object'){
display = print(object[elem]);
} else {
display = object[elem];
}
return `${elem.charAt(0).toUpperCase()}${elem.slice(1)}: ${display}`;
});
console.log(objMap.join('\n'));
}

关于javascript - .join() 函数在 map 函数中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58491777/

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