简体   繁体   中英

How to filter the array of objects based on array of strings by using angular6

I have 2 arrays of string and 1 array of objects. I need to filter based on 2 arrays of string. how can I achieve this?

let profissionals = [
{state:'ap',type:'maths',price:200},
{state:'ap',type:'english',price:400},
{state:'ka',type:'social',price:200},
{state:'ts',type:'english',price:200},
{state:'ap',type:'maths',price:500},
{state:'ka',type:'maths',price:600},
{state:'ts',type:'english',price:200},
{state:'kl',type:'english',price:100},
{state:'kl',type:'english',price:300},
{state:'ap',type:'social',price:200},
{state:'gj',type:'english',price:600},
{state:'kl',type:'social',price:600}
]

let typeList=['maths','social'];
let stateList=['ap','ka'];

the output should be like this

fliteredlist  = [
{state:'ap',type:'maths',price:200},
{state:'ap',type:'maths',price:500},
{state:'ka',type:'maths',price:600},
{state:'ap',type:'social',price:200},
{state:'ka',type:'social',price:200},
]

You can use Array.filter() :

 let profissionals = [ {state:'ap',type:'maths',price:200}, {state:'ap',type:'english',price:400}, {state:'ka',type:'social',price:200}, {state:'ts',type:'english',price:200}, {state:'ap',type:'maths',price:500}, {state:'ka',type:'maths',price:600}, {state:'ts',type:'english',price:200}, {state:'kl',type:'english',price:100}, {state:'kl',type:'english',price:300}, {state:'ap',type:'social',price:200}, {state:'gj',type:'english',price:600}, {state:'kl',type:'social',price:600} ] let typeList=['maths','social']; let stateList=['ap','ka']; let output = profissionals.filter(({type, state}) => (typeList.length === 0 || typeList.includes(type)) && (stateList.length === 0 || stateList.includes(state))); console.log(output);

profissionals.filter(({state, type}) => stateList.includes(state) && typeList.includes(type));

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