说用户可以在这里example.com/?page=1&q=123
我可以得到
[{page: 1}, {q: 123}]
使用图书馆
但是说我想用[{page: 1}]
做某事仍然很危险,因为用户可以输入我不需要的额外参数。
所以我的想法是我提供一个预设
const preset = [{page: 1}, {valid: true}]
如何获得[{page: 1}, {valid: true}] from says [{page: 1}, {valid: true}, {abc: 123}, {other: 'others'}]
?
答案 0 :(得分:0)
var arr = [{page: 1}, {valid: true}, {abc: 123}, {other: 'others'}];
var result = arr.filter(x => Object.keys(x).includes('page') || Object.keys(x).includes('valid'));
console.log(result);
答案 1 :(得分:0)
使用filter
和Object.keys
遍历数组并检查返回键obj
const mixArray = [{page: 1}, {valid: true}, {abc: 123}, {other: 'others'}];
function filterRequiredObj(arr=[],filters=[]){
return arr.filter((f)=>{
const keys= Object.keys(f)[0];
if(filters.includes(keys)) return f
})
}
const newArray = filterRequiredObj(mixArray,['page','valid'])
console.log('newArray',newArray)