迭代对象值 - javascript

时间:2018-05-26 21:46:34

标签: javascript

鉴于此数据结构:

{ "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做到这一点?谢谢!

2 个答案:

答案 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"))




  1. 使用Object.values方法
  2. 获取对象中键的值
  3. map在他们身上
  4. 由于值本身是Array,因此将其强制转换为字符串(或获取第一个元素)
  5. 用新行加入他们

答案 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
}