0
var test = [
    {
        id   : 'user01',
        pos0 : 2 
    },
    {
        id   : 'user01',
        pos0 : 3 
    },
    {
        id   : 'user02',
        pos1 : 5 
    },
    {
        id   : 'user02',
        pos1 : 6 
    },
    {
        id   : 'user03',
        pos2 : 8 
    },
    {
        id   : 'user03',
        pos2 : 9 
    }
]

This is example data,

and I want if I passed 'pos2', get test[4] and test[5].

//like this : 

function getObjectByKey(array, key){
    // dosomething
};

..
var testArray = getObjectByKet(test, 'pos2');

I tried to use $.inArray or $.map, but how to use them. How can i do this?

Regards.

vvThat
  • 157
  • 2
  • 13

2 Answers2

1

Please try this,

 function getObjectByKey(array, key){
        var users=[];
        $.map(array, function (user, index) {
            if (user[key])
                users.push(user)
        });
        return users;
    };

hope this will help you.

Also change your function calling. You miss spelled the function name Try this while calling the method

var testArray = getObjectByKey(test, 'pos2');
balachandar
  • 825
  • 4
  • 13
0

I would suggest to use Array.prototype.map() method to iterate an array. Like this:

var test = [
    {
        id   : 'user01',
        pos0 : 2 
    },
    {
        id   : 'user01',
        pos0 : 3 
    },
    {
        id   : 'user02',
        pos1 : 5 
    },
    {
        id   : 'user02',
        pos1 : 6 
    },
    {
        id   : 'user03',
        pos2 : 8 
    },
    {
        id   : 'user03',
        pos2 : 9 
    }
]
var user;
test.map(function(v) { if(v.id == 'user03') user = v;  }); 

Here is a FIDDLE.

Alexandr Lazarev
  • 12,554
  • 4
  • 38
  • 47