1

I want to be able to get all the keys from an object. Assuming the object looks like below:

            this.reservation = {
            "Firstname" : "" ,
            "Lastname" :"" ,
            "Phone" : "",
            "Email" : "",
            "Date" : "yyyy-mm-dd hh:mm",
            "Starthour" : "",
            "Endhour" : "",
            "Persons" : ""
        }

If I want to be able to check whether all the keys' values are "", except Date of course, how would I go about doing that?

I've tried to do a forEach to get the keys:

            angular.forEach(this.reservation,
            function(value, key) {
                console.log(key);
            });

But it doesn't work. Any hints?

3 Answers 3

9

try this,

Object.keys(reservation);
Sign up to request clarification or add additional context in comments.

Comments

1

You can use Object.keys and some functional Array methods

var allEmptyExceptDate = Object.keys(this.reservation)
  .filter(function(key) { return key !== 'Date'; }) // all except 'Date'
  .every(function(key) { return !this.reservation[key] })  // are falsy (i.e. empty or undefined or null) - or you can use this.reservation[key] === '' for a more precise check

Comments

0

For objects you can use the for in loop

Pure javascript way of doing this:

for(prop in this.reservation){ 
    if(typeof this.reservation[prop] === "string"){
         console.log(prop + 'value ' + "is a string");
    } 
}

Angular way:

angular.forEach(this.reservation, function(value, key){
    if(typeof value === "string"){
        console.log(value + ' is of type string');
    }
}

1 Comment

Urm.. angular.forEach can definitely iterate through objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.