简体   繁体   中英

Validate route params as array of object

Says user can go here example.com/?page=1&q=123

I can get [{page: 1}, {q: 123}]

using a library

But this is still can be dangerous says I want to use [{page: 1}] for something because the user can enter extra params which I don't need.

so the idea is I provide a preset const preset = [{page: 1}, {valid: true}]

how can I get [{page: 1}, {valid: true}] from says [{page: 1}, {valid: true}, {abc: 123}, {other: 'others'}] ?

 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); 

Use filter and Object.keys to iterate through the array and by checking key return 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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM