如何在javascript数组中创建动态键和valuse

时间:2015-08-19 16:51:26

标签: javascript arrays

输入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]

1 个答案:

答案 0 :(得分:2)

使用filtersome检查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]

DEMO

更新

在回家的路上意识到,实际上你并不需要some。此外,要回答您的评论,请按照以下方式搜索passgender

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]

DEMO