1

I have the following object.

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

I would like to print this:

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

So basically, I want to be able to iterate through the values of the object. How can I do this in JavaScript?

1
  • for( let el of Object.values( obj ) ) { console.log( obj[0] ); } Commented May 26, 2018 at 21:49

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

While not explicitly stated these look like validation messages; an array of validation messages per field makes sense.
@AndyGaskell Could be, but that's not actually known. That's why I'm showing both approaches.
Right on, while typing my comment your answer only showed one approach.
3

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.