我坚持使用for循环结构。 我需要获取一个对象数组的属性名称,但我只是获取数组名称而不是属性。有人帮助我。
let employes = [
{
name: 'iagor',
age: 22,
role: 'front-end developer'
},
{
name: 'jasiel',
age: 21,
role: 'illustrator'
},
{
name: 'davi',
age: 32,
role: 'movie maker'
}
];
for (let employe in employes) {
console.log(`${Object.keys(employes[0])}: ${employes[employe].name}`);
console.log(`${Object.keys(employes[0])}: ${employes[employe].age}`);
console.log(`${Object.keys(employes[0])}: ${employes[employe].role}\n`);
}
输出:
name,age,role: iagor
name,age,role: 22
name,age,role: front-end developer
答案 0 :(得分:0)
你必须首先遍历数组。你可以这样试试。
for (let employe of employes) {
for (let key in employe) {
console.log (key, employe[key]);
}
console.log ('\n');
}
答案 1 :(得分:0)
您必须首先遍历数组。由于数组中的每个元素都是一个对象,您可以使用object.keys来获取项的属性和值
检查此代码段
let employes = [{
name: 'iagor',
age: 22,
role: 'front-end developer'
}, {
name: 'jasiel',
age: 21,
role: 'illustrator'
}, {
name: 'davi',
age: 32,
role: 'movie maker'
}];
employes.forEach(function(employee) {
Object.keys(employee).forEach(function(item) {
console.log(item+":" + employee[item]);
});
});
希望这有帮助
答案 2 :(得分:0)
employes.forEach((employ) => {
Object.keys(employ).forEach((propName) => {
console.log(`${propName}: ${employ[propName]}`)
});
});