过滤列表对象与列表列表字符串(动态)



我确实在Stack Overflow上搜索,但我仍然感到困惑。我确实在Stack Overflow上搜索过,但我仍然很困惑。我确实在Stack Overflow上搜索过,但我仍然很困惑。


//There are two JavaScript arrays: a and array: b
var a = [
{
inputList:['S','600 gram']
},
{
inputList:['X','800 gram']
}
];
var b = [
{Size: 'S', productVariantId: '8cb8eaed-7310-41a5-a717-8ccc6694c52c', Weight: '600 gram'},
{Size: 'S', productVariantId: 'a2c3b56f-075f-4c65-8f5c-a0cd188a735b', Weight: '800 gram'},
{Size: 'X', productVariantId: '8cb8eaed-7310-41a5-a717-8ccc6694c52c', Weight: '600 gram'},
{Size: 'X', productVariantId: 'a2c3b56f-075f-4c65-8f5c-a0cd188a735b', Weight: '800 gram'}
];
expect c=[
{Size: 'S', productVariantId: '8cb8eaed-7310-41a5-a717-8ccc6694c52c', Weight: '600 gram'},
{Size: 'X', productVariantId: 'a2c3b56f-075f-4c65-8f5c-a0cd188a735b', Weight: '800 gram'}
]
a & b is dynamic it can changes 
ex: b=[
{Color: 'S', productVariantId: '8cb8eaed-7310-41a5-a717-8ccc6694c52c', Styles: '600 gram'}
]
filter array 2 from condition is array 1
I want to expect c=[
{Size: 'S', productVariantId: '8cb8eaed-7310-41a5-a717-8ccc6694c52c', Weight: '600 gram'},
{Size: 'X', productVariantId: 'a2c3b56f-075f-4c65-8f5c-a0cd188a735b', Weight: '800 gram'}
]

直接方式

const filtered = b.filter(
(element) => {
return  (element.Size === a[0].inputList[0] &&  element.Weight === a[0].inputList[1]) ||  (element.Size === a[1].inputList[0] &&  element.Weight === a[1].inputList[1]) 
}
)

为B(您的数据源)输入更好

type B = {productVariantId:string; [key :string]: string}
const b : Array<B> = [
{Size: 'S', productVariantId: '8cb8eaed-7310-41a5-a717-8ccc6694c52c', Weight: '600 gram'},
{Size: 'S', productVariantId: 'a2c3b56f-075f-4c65-8f5c-a0cd188a735b', Weight: '800 gram'},
{Size: 'X', productVariantId: '8cb8eaed-7310-41a5-a717-8ccc6694c52c', Weight: '600 gram'},
{Size: 'X', productVariantId: 'a2c3b56f-075f-4c65-8f5c-a0cd188a735b', Weight: '800 gram'}
];
const myfilter2 = (source : Array<B>, filters : typeof a) => {
return source.filter(
(element) => {
for(const filterParams of a) {
const keep = element.Size === filterParams.inputList[0] &&  element.Weight === filterParams.inputList[1];
if(keep) return true;
}
return false;
}
)
}

假设过滤器的大小总是重量和.


If过滤器也应该是动态的你应该继续输入a:

type A = { inputList: Array<{ [key: string]: string }> };
const a2: Array<A> = [
{
inputList: [{ Size: 'S', Weight: '600 gram' }]
},
{
inputList: [{ Size: 'X', Weight: '800 gram' }]
}
];
const myfilter3 = (source : Array<B>, filters : Array<A>) => {
return source.filter(
(element) => {
for(const filterParams of filters) {
let keep = true;
for(const filter of filterParams.inputList){
for(const key of Object.keys(filter)){
keep = keep && element[key] === filter[key] ;
}
if(keep) return true
}
}
return false;
}
)
}

最新更新