1

I've been going through hell trying to figure this out, i'm sure it's not that big of a deal, perhaps i'm just tired from coding all night, but I could really use some help...

"users" is a database-like object containing user account information ( server-side, of course ), "get" is a function that returns an array of matching objects from the users array.

var users = [
    {
        name:"xymon",   
            age:19,
        pass:"mypass",  
        time:1364101200684
    },
    {
        name:"test",    
            age:19,
        pass:"x",   
        time:1364101200993
    },
    {
            name:"test",
            age:19,
            pass:"bleh",
            time:1364101200992
    }

];

function get(a){

}

What I'm wanting "get" to do is return properties that match the specified object (a) in an array, like so...

var matching_users = get({name:"test",age:19});

This would return the two objects in the "users" array because their properties match the specified properties in "get" so that "matching_users" would return as...

[
    {
        name:"test",    
            age:19,
        pass:"x",time:1364101200993
    },
    {
            name:"test",
            age:19,
            pass:"bleh",
            time:1364101200992
    }

]

3 Answers 3

2

Iterate your array and check each item for matching:

function get(a){
var r = [];
for (var i=0, len=users.length; i<len; ++i) {
    var doAdd = true;
    for (var p in a) {
        if (a.hasOwnProperty(p)) {
            if (a[p] != users[i][p]) {
                doAdd = false;
                break;
            }
        }            
    }    
    if (doAdd)
        r.push(users[i]);
}
return r;
}
Sign up to request clarification or add additional context in comments.

Comments

1
function get(a) {
  var matches = [];

  for (var i in users) {
     var matched = true;

     for (var prop in a) {
         if (a.hasOwnProperty(prop) && users[i][prop] !== a[prop]) {
             matched = false;
             break;
         }
     }

     if (matched) matches.push(users[i]);
  }

  return matches;
}

1 Comment

if Object.prototype has a additional properties, you'll make redundant iterations
0
 function get(a) {
 var result = [];
      users.forEach(function (v, i) {
           if (v.name == a.name && v.age == a.age) {
                result.push(v);               
           }
 });

Result will be the array with matched objects.

Comments

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.