我下面有一群人
<div class="container">
<img src="https://ichef.bbci.co.uk/news/660/cpsprodpb/A825/production/_103954034_gettyimages-990971906.jpg">
<h3>LOREM IMPSUM</h3>
</div>
我想过滤数组以基于“过滤器”对象生成单独的数组。
例如,如果我的过滤器是:
.container {
height: 40vw;
width: 40vw;
border: 1px solid black;
display:grid;
position: relative;
}
img {
max-width: 100%;
max-height:100%;
height: 100%;
width: 100%;
object-fit: contain;
object-position: left top;
}
h3 {
position: absolute;
left: 50%;
transform: translate(-50%, -10vw);
top: 20vw;
}
新数组应为空,因为数组中没有人具有32和John的组合。但是,如果我的过滤器是:
const FIRST_ARRAY = [
{
name: 'Simon',
age: 32,
occupation: 'Student'
},
{
name: 'Vera',
age: 22,
occupation: 'Developer'
}
];
返回的新人群是:
const FILTERS = {
age: 32,
name: 'John',
occupation: ''
};
如何通过遍历“过滤器”对象值来过滤人员阵列?切记,过滤器的键和值将一直动态变化。
答案 0 :(得分:1)
您可以进行以下过滤:
const FIRST_ARRAY = [
{
name: 'Simon',
age: 32,
occupation: 'Student'
},
{
name: 'Vera',
age: 22,
occupation: 'Developer'
}
];
const FILTERS = {
name: 'Simon',
age: 32,
occupation: ''
};
const filtered = FIRST_ARRAY.filter(person => Object.entries(FILTERS)
.every(([key, val]) => val !== '' ? person[key] === val : true));
console.log(filtered);
答案 1 :(得分:0)
您可以使用函数const data = [{
id: 1,
cod: '123',
val: true
},
{
id: 2,
cod: '123',
val: true
},
{
id: 3,
cod: '123',
val: true
},
{
id: 4,
cod: '456',
val: true
},
{
id: 5,
cod: '456',
val: true
}];
const previousCod = new Map();
for (const item of data) {
if (previousCod.has(item.cod)) {
previousCod.get(item.cod).val = false;
}
// Can be omitted if the initial value is guaranteed to be `true`
item.val = true;
previousCod.set(item.cod, item);
}
console.log(data);
和函数filter
来检查每个键值是否等于every
值。
假设当FILTERS中的值为空时,请跳过该值
FILTERS
const FIRST_ARRAY = [{name: 'Simon',age: 32,occupation: 'Student'},{name: 'Vera',age: 22,occupation: 'Developer'}],
FILTERS = {age: 32,name: 'Simon',occupation: ''},
keys = Object.keys(FILTERS),
result = FIRST_ARRAY.filter(o => keys.every(k => FILTERS[k] === '' || FILTERS[k] === o[k]));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:0)
您可以尝试以下方法:
function compare(item, filter) {
for (var property in filter) {
if (filter.hasOwnProperty(property)) {
let value = filter[property];
return item.hasOwnProperty(property) && item[property] != '' && value == item[property];
}
}
}
const DATA = [
{
name: 'Simon',
age: 32,
occupation: 'Student'
},
{
name: 'Vera',
age: 22,
occupation: 'Developer'
}
];
const filter = {
age: 32,
name: 'Simon',
occupation: ''
};
let result = DATA.filter(function(item) {
return compare(item, filter);
})
console.log(result);