输入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"]}
如何创建新数组..根据传递数字推送ID
Ex:在循环显示中
passid => 2 .... eid => 12,20
2 ==> ["12","20"]
1 ==> [12, 11]
3 ==> [11,20]
答案 0 :(得分:2)
使用filter
和some
检查pass
数组的内容,然后返回相应的eid
值:
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]
更新
在回家的路上意识到,实际上你并不需要some
。此外,要回答您的评论,请按照以下方式搜索pass
和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]