我想知道如何根据javascript中的条件进行过滤。
如果
min
存在,amt > min
,还有whole obj
,
remove that particular object in the obj
function getItem(obj){
return
obj.filter(e=>e.hasOwnProperty("min")?e.amt>e.min:e);
}
var obj1=[{
"id": "name",
"min": 300,
"amt": 200,
"cn" : "SG"
},{
"id": "others",
"amt": 200,
"cn" : "TH"
},{
"id": "others",
"amt": 200,
"cn" : "TH"
}]
var obj2=[{
"id": "name",
"min": 300,
"amt": 500,
"cn" : "SG"
},{
"id": "others",
"amt": 200,
"cn" : "TH"
},{
"id": "others",
"amt": 200,
"cn" : "TH"
}]
预期输出: var result = getItem(obj1);
[{
"id": "others",
"amt": 200,
"cn" : "TH"
},{
"id": "others",
"amt": 200,
"cn" : "TH"
}]
var result = getItem(obj2);
[{
"id": "name",
"min": 300,
"amt": 500,
"cn" : "SG"
},{
"id": "others",
"amt": 200,
"cn" : "TH"
},{
"id": "others",
"amt": 200,
"cn" : "TH"
}]
答案 0 :(得分:0)
检查是否存在min
,如果不返回,则检查对象是否大于amt
。
var obj1 = [{
"id": "name",
"min": 300,
"amt": 200,
"cn": "SG"
}, {
"id": "others",
"amt": 200,
"cn": "TH"
}, {
"id": "others",
"amt": 200,
"cn": "TH"
}]
var obj2 = [{
"id": "name",
"min": 300,
"amt": 500,
"cn": "SG"
}, {
"id": "others",
"amt": 200,
"cn": "TH"
}, {
"id": "others",
"amt": 200,
"cn": "TH"
}];
const res1 = obj1.filter(({
min,
amt
}) => {
return !min || (amt > min);
});
console.log(res1);
const res2 = obj2.filter(({
min,
amt
}) => {
return !min || (amt > min);
});
console.log(res2);
答案 1 :(得分:0)
如果我正确理解了您的问题,则仅当对象包含amt > min
时,才希望应用条件min
。如果对象不包含min
,则返回整个对象。
在这种情况下,getItem
应该看起来像这样:
const getItem = arrayOfObjects => arrayOfObjects.filter(obj => {
if (obj['min']) {
if (obj['amt'] > obj['min']) return true
} else {
return true
}
})
答案 2 :(得分:0)
这是我尝试过的一种解决方法
function getItem(obj) {
return !('min' in obj) || obj.amt>obj.min ;
}
var obj1 = [{
"id": "name",
"min": 300,
"amt": 200,
"cn": "SG"
}, {
"id": "others",
"amt": 200,
"cn": "TH"
}, {
"id": "others",
"amt": 200,
"cn": "TH"
}]
var obj2 = [{
"id": "name",
"min": 300,
"amt": 500,
"cn": "SG"
}, {
"id": "others",
"amt": 200,
"cn": "TH"
}, {
"id": "others",
"amt": 200,
"cn": "TH"
}]
var result1 = obj1.filter(getItem);
var result2 = obj2.filter(getItem);
console.log('result1',result1);
console.log('result2',result2);