我有两个数组,其中包含我要从员工数组中删除的ID列表。
在Java脚本中执行此操作的最佳方法是什么?我可以使用任何ES6语法
{
"excludeIDArray": [
1,
3,
4
]
}
{
"employee": [
{
"id": "1",
"name": "joe"
},
{
"id": "2",
"name": "john"
},
{
"id": "3",
"name": "mike"
},
{
"id": "4",
"name": "alex"
},
{
"id": "5",
"name": "sean"
}
]
}
我希望输出是一个看起来像
的数组{
"employee": [
{
"id": "2",
"name": "john"
},
{
"id": "5",
"name": "sean"
}
]
}
答案 0 :(得分:4)
只需使用Array.prototype.filter
,Array.prototype.indexOf
和parseInt
(将字符串ID转换为数字)。
const exc = {"excludeIDArray":[1,3,4]}
const inObj = {"employee":[{"id":"1","name":"joe"},{"id":"2","name":"john"},{"id":"3","name":"mike"},{"id":"4","name":"alex"},{"id":"5","name":"sean"}]}
const outObj = {
employee: inObj.employee.filter(e => exc.excludeIDArray.indexOf(parseInt(e.id, 10)) === -1)
}
console.log(outObj);
您也可以使用Array.prototype.includes
(如果可用)代替Array.prototype.indexOf
,因为它更具可读性
e => !exc.excludeIDArray.includes(parseInt(e.id, 10))
另一种选择是将您的排除数组转换为Set
,这样可以获得更好的(O(1)
)效果
const exc = {"excludeIDArray":[1,3,4]}
const inObj = {"employee":[{"id":"1","name":"joe"},{"id":"2","name":"john"},{"id":"3","name":"mike"},{"id":"4","name":"alex"},{"id":"5","name":"sean"}]}
const exclude = new Set(exc.excludeIDArray)
const outObj = {
employee: inObj.employee.filter(e => !exclude.has(parseInt(e.id, 10)))
}
console.info(outObj)
答案 1 :(得分:2)
使用地图进行过滤而不是indexOf
,以便更快地进行线性时间过滤
var exclusion = {"excludeIDArray": [1, 3, 4]};
var data = {"employee":[{"id":"1","name":"joe"},{"id":"2","name":"john"},{"id":"3","name":"mike"},{"id":"4","name":"alex"},{"id":"5","name":"sean"}]};
var exclusionMap = {};
exclusion.excludeIDArray.forEach(excludeId=>{exclusionMap[excludeId] = 1});
var filteredEmployees = data.employee.filter(employee=>{return exclusionMap[employee.id] === undefined});
console.log(filteredEmployees);