鉴于此数据结构:
{ "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做到这一点?谢谢!
答案 0 :(得分:3)
让我们看看:
const obj = { "name": [ "can't be blank" ], "league_id": [ "You already have a team in this league." ] }
console.log(Object.values(obj).map(value => value.toString()).join("\n"))

Object.values
方法map
在他们身上答案 1 :(得分:2)
您的数据结构没有多大实际意义,因为您的属性值是只包含一个元素的数组。虽然合法,但对于您显示的数据,将字符串作为值更有意义。
无论哪种方式,对象上的 for/in
循环都允许您迭代键。
目前的结构:
.chapter

删除数组:
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
}

您还可以使用 Object.keys(obj)
以及 .forEach()
方法调用,这是一种较新的技术:
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
}