我正在尝试使用map函数遍历以下格式的对象:
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
答案 0 :(得分:1)
因为您有嵌套的对象。 object [elem] .join不起作用join是一个数组函数,它将仅与Array一起使用。像下面一样
"currencies": [
{
"code": "HKD",
"name": "Hong Kong dollar",
"symbol": "$"
}
]
如果用于数组,您将需要再添加一个,并且在存在嵌套对象时将需要使用递归函数
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'));
}
答案 1 :(得分:0)
您的代码工作正常。所有数组都是javascript中的对象,因此typeof可能无济于事。
.join是一个数组方法,为确保在有效数组上运行,我将使用Array.isArray()而不是typeof。
如果传入的值是Array,则Array.isArray()返回true;否则,则返回false。
在处理嵌套对象/数组时,我同意上面的Shashi。
当您必须评估正在使用的数据类型时,一个简单的while循环将起作用。