简体   繁体   中英

Iterate through object values - javascript

Given this data structure:

{ "name": [ "can't be blank" ], "league_id": [ "You already have a team in this league." ] }

How can I print this?

Can't be blank
You already have a team in this league

So basically I want to iterate through the values of the object. How can I do this with Javascript? Thank You!

Let's see:

 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. Get values of the keys in object with Object.values method
  2. map over them
  3. Since the value itself is Array, cast it to string (or get the first element)
  4. Join them with a new line

Your data structure doesn't make much practical sense in that your property values are arrays with just one element in them. While legal, for the data you are showing, it makes more sense just to have the strings as the values.

Either way, a for/in loop over the object will allow you to iterate the keys.

With current structure:

 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 } 

With arrays removed:

 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 } 

You can also use Object.keys(obj) , along with a .forEach() method call, which is a newer technique:

 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 }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM