我有以下对象。
{ "name": [ "Can't be blank" ], "league_id": [ "You already have a team in this league." ] }
我想打印这个:
Can't be blank
You already have a team in this league
基本上,我希望能够迭代对象的值。我怎样才能在 JavaScript 中做到这一点?
最佳答案
您的数据结构没有多大实际意义,因为您的属性值是其中只有一个元素的数组。虽然合法,但对于您显示的数据,将字符串作为值更有意义。
无论哪种方式, for/in
遍历对象将允许您迭代键。
当前结构:
let obj = {
"name": ["can't be blank"],
"league_id": ["You already have a team in this league."]
};
for(var key in obj){
console.log(obj[key][0]); // Here, you have to index the property value, which is an array
}
删除数组后:
let obj = {
"name": "can't be blank",
"league_id": "You already have a team in this league."
};
for(var key in obj){
console.log(obj[key]); // Here, you can access the key value directly
}
您还可以使用Object.keys(obj)
,以及 .forEach()
方法调用,这是一种较新的技术:
let obj = {
"name": ["can't be blank"],
"league_id": ["You already have a team in this league."]
};
Object.keys(obj).forEach(function(key){
console.log(obj[key][0]); // Here, you have to index the property value, which is an array
});
关于javascript - 迭代对象值 - javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50547252/