Reputation: 761
Input JSON
0===>{"eid":12,"gender":"1","age":1,"pass":["2","1"]}
1===>{"eid": 11,"gender":"0","age":1,"pass":["1","3"]}
2===>{"eid":20,"gender":"1","age":1,"pass":["2","3"]}
how to create new array.. to push the ids based on the pass numbers
Ex: IN a loop display
passid => 2 .... eid => 12, 20
2 ==> ["12","20"]
1 ==> [12, 11]
3 ==> [11,20]
Upvotes: 0
Views: 43
Reputation: 63524
Use filter
and some
to check the contents of the pass
array and then return the respective eid
values:
function grabber(data, pass) {
return data.filter(function (el) {
return el.pass.some(function (num) {
return +num === pass;
})
}).map(function (el) {
return el.eid;
});
}
grabber(data, 1); // [12, 11]
grabber(data, 2); // [12, 20]
grabber(data, 3); // [11, 20]
UPDATE
Realised on the way home from work you don't actually need some
. Further, to answer your comment, here's how you might search for pass
and gender
:
function grabber(data, options) {
return data.filter(function (el) {
return el.pass.indexOf(options.pass) > -1 && el.gender === options.gender;
}).map(function (el) {
return el.eid;
});
}
grabber(data, { gender: '0', pass: '1' }); // [11]
Upvotes: 2