我试图创建一个字典(我认为这是最好的选择......)来设置一种地址簿。想法是返回像
这样的东西contacts = {"Bruce Wayne":{"phone number":'123-456-7890', "car":"All of them"}, "Alfred":{"phone number" :'987-654-3210', "car": "limo"}, "Clark Kent":{"phone number":'951-753-8520', "car":"None, flying works."}}
这很有效。我可以说console.log(contacts["Bruce Wayne"])
并返回:
{'电话号码':' 123-456-7890',car:'所有人' }
正确返回<{p}}
123-456-7890
但是,我无法弄清楚如何遍历每个人,然后是每个人console.log(contacts["Bruce Wayne"]["phone number"])
和phone number
。
使用此:
car
只返回
[object Object]
[对象]
[object Object]
我试图获得(伪代码)
for (const[key, value] of Object.entries(contacts)){
console.log(contacts[key]);
}
布鲁斯·韦恩,电话号码是123-456-7890,车就是所有人 阿尔弗雷德,电话号码是987-654-3210,车是豪华轿车
编辑:我也试过了
[First key], [key] is [value], [key] is [value]
也返回for (var person in contacts){
console.log(contacts[person])
}
...
答案 0 :(得分:0)
试试这个:
for (let i in contacts) {
console.log(i + ',' + JSON.stringify(contacts[i]).replace(/\":\"/g, ' is ').replace(/["{}]/g, ''));
}
或
let contacts = { "Bruce Wayne": { "phone number": '123-456-7890', "car": "All of them" }, "Alfred": { "phone number": '987-654-3210', "car": "limo" }, "Clark Kent": { "phone number": '951-753-8520', "car": "None, flying works." } }
function consoleObj(obj, separator, attrIntro) {
let result = '';
for (let name in obj) {
result += name + separator;
for (let attr in obj[name]) {
result += attr + attrIntro + obj[name][attr] + separator;
}
result += '\n';
}
return result;
}
console.log(consoleObj(contacts, ',', ' is '));
或者
function consoleObj(obj, separator, attrIntro) {
return Object.keys(obj).reduce(function(result, name) {
result += name + separator;
Object.keys(obj[name]).forEach(function(attr) {
result += attr + attrIntro + obj[name][attr] + separator;
});
result += '\n';
return result;
}, '');
}
console.log(consoleObj(contacts,',',' is '));
答案 1 :(得分:-2)
您的for..of循环为您提供了包含属性的名称和对象,因此您需要更改访问"phone number"
和"car"
到details['phone number']
等的方式。
const contacts = {"Bruce Wayne":{"phone number":'123-456-7890', "car":"All of them"}, "Alfred":{"phone number" :'987-654-3210', "car": "limo"}, "Clark Kent":{"phone number":'951-753-8520', "car":"None, flying works."}}
// join an object
const joinObject = (obj, glue = 'is', joiner = ', ') =>
Object.keys(obj)
.map(k => `${k} ${glue} ${obj[k]}`)
.join(joiner)
// fixed string
for (const [name, details] of Object.entries(contacts)) {
console.log(`${name}, phone number is ${details['phone number']}, car is ${details['car']}`);
}
// dynamic property description
for (const [name, details] of Object.entries(contacts)) {
console.log(name + ' ' + joinObject(details))
}