Ajey
Ajey

Reputation: 8202

Ember js check for key value in array of objects

I have an users array which consists of 4 user objects.

users: [
        {
            id: 1,
            user_id: 10116,
            email: "[email protected]",
            password: "[email protected]"
        },
        {
            id: 2,
            user_id: 10117,
            email: "[email protected]",
            password: "[email protected]"
        },
        {
            id: 4,
            user_id: 10126,
            email: "[email protected]",
            password: "[email protected]"
        }
    ]

var myEmail = "[email protected]";
var myPassword = "[email protected]";

What is the shortest way to check wether a particular myEmail & myPassword exists/matches in the given users array.

Is there any Ember way of doing this ?

I have tried using the forEach loop and trying to check for values. I am looking for an optimal soluton.

Thx

Upvotes: 0

Views: 3537

Answers (2)

Matthew Blancarte
Matthew Blancarte

Reputation: 8301

Before I answer, a word of caution. You are putting your users at extreme risk by exposing passwords in any form to the client. Doesn't matter how you encrypted them or whatever.

That said, you are likely looking for .any http://emberjs.com/api/classes/Ember.Array.html#method_any

It will return true (boolean) if your condition matches one or more items in the enumeration. I often use this in computed properties. For example, here is what it might look like it you were looping that collection into a template and you wanted to work within an item controller:

matchedEmailAndPassword: function () {
  return this.get('users').any(function (item) {
    return item.get('email') === this.get('email') && item.get('password') === this.get('password');
}.property('email', 'password')

I wouldn't actually use that computed property, it's just pseudo code.

Hope that helps!

Upvotes: 1

Chris HG
Chris HG

Reputation: 1492

It's not quite one line, but using just inbuilt Javascript, the most concise I can come up with is:

var user = users.filter(function (element) {
  return element.email == myEmail && element.password == myPassword;
})[0];

Here's a working jsFiddle: http://jsfiddle.net/dqMLG/

Upvotes: 2

Related Questions