过滤驱动程序ID

时间:2018-01-12 11:04:53

标签: javascript

我想要的是如果驱动程序在BusyAgent中,那么freedriver的最终输出应该包含来自fetchAgent的所有输入 那些在busyAgent。

预期输出 [{ “标记”: “”, “阵列”:[{ “DEVICE_TYPE”:0 “fleet_id”:23691, “ETA”:0}]}]

var fetchAgent = [{
    "tag": "",
    "array": [{
        "device_type": 0,
        "fleet_id": 24117,
        "eta": 0
    }]
}, {
    "tag": "",
    "array": [{
        "device_type": 0,
        "fleet_id": 23691,
        "eta": 0
    }]
}];


var busyAgent = ['24102', '24103', '24117'];

//Cannot read property 'filter' of undefined

if (Array.isArray(busyAgent) && busyAgent.length > 0) {
    freeDrivers = fetchAgent.map(e => {
        e.array = e.array.filter(a => busyAgent.indexOf("" + a.fleet_id))
        return e;
    });
} else {
    freeDrivers = fetchAgent;
}
console.log(JSON.stringify(freeDrivers));

2 个答案:

答案 0 :(得分:1)

以更简单的方式使用Array的filter()尝试以下操作:

var fetchAgent = [{
    "tag": "",
    "array": [{
        "device_type": 0,
        "fleet_id": 24117,
        "eta": 0
    }]
}, {
    "tag": "",
    "array": [{
        "device_type": 0,
        "fleet_id": 23691,
        "eta": 0
    }]
}];


var busyAgent = ['24102', '24103', '24117'];

var output = fetchAgent.filter(function(item){
  return !busyAgent.includes(item.array[0].fleet_id.toString())
});

console.log(JSON.stringify(output))

答案 1 :(得分:1)

反转过滤器大小写,也可以将map替换为filter,这样就不会有空值。否则,您将不得不在路上进行另一次过滤。

var fetchAgent = [{
    "tag": "",
    "array": [{
        "device_type": 0,
        "fleet_id": 24117,
        "eta": 0
    }]
}, {
    "tag": "",
    "array": [{
        "device_type": 0,
        "fleet_id": 23691,
        "eta": 0
    }]
}];


var busyAgent = ['24102', '24103', '24117'];
if (Array.isArray(busyAgent) && busyAgent.length > 0) {
    freeDrivers = fetchAgent.filter(e => {
        e.array = e.array.filter(a => busyAgent.indexOf("" + a.fleet_id) < 0);
        if( e.array.length > 0) return e;
    });
} else {
    freeDrivers = fetchAgent;
}

console.log(JSON.stringify(freeDrivers));