假设我们有一个像这样的对象数组-
const arr = [ {area: 'NY', name: 'Bla', ads: true}, {area: 'DF', name: 'SFS', ads: false}, {area: 'TT', name: 'SDSD', ads: true}, {area: 'SD', name: 'Engine', ads: false}, {area: 'NSK', name: 'Toyota', ads: false}, ];
我们需要编写一个JavaScript函数,该函数接受一个数组作为第一个参数,并将字符串文本数组作为第二个参数。
然后,我们的函数应过滤输入对象数组,以仅包含其“ area”属性包含在文字数组(第二个参数)中的那些对象。
为此的代码将是-
const arr = [ {area: 'NY', name: 'Bla', ads: true}, {area: 'DF', name: 'SFS', ads: false}, {area: 'TT', name: 'SDSD', ads: true}, {area: 'SD', name: 'Engine', ads: false}, {area: 'NSK', name: 'Toyota', ads: false}, ]; const keys = ['NY', 'SD']; const filterByArea = (arr = [], keys = []) => { const res = []; for(let i = 0; i < arr.length; i++){ const { area } = arr[i]; if(keys.includes(area)){ res.push(arr[i]); }; }; return res; }; console.log(filterByArea(arr, keys));
输出结果
控制台中的输出将是-
[ { area: 'NY', name: 'Bla', ads: true }, { area: 'SD', name: 'Engine', ads: false } ]