0

I would like to know how to filter based on condition in javascript. If the min is present and amt > min, get whole obj else, 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"
}]


Expected Output: 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"
}]

Senthil
  • 961
  • 1
  • 8
  • 21
  • Possible duplicate of [How to filter object array based on attributes?](https://stackoverflow.com/questions/2722159/how-to-filter-object-array-based-on-attributes) – marvinhagemeister Aug 07 '19 at 08:32

3 Answers3

0

Check for existence of min, if not return the object else check if it is greater than 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);
random
  • 7,756
  • 3
  • 19
  • 25
0

If I understand your question correctly, you only want to apply the condition amt > min if and only if the object contains min. If the object doesn't contain min, then return the whole object.

In that case, getItem should look like this:

const getItem = arrayOfObjects => arrayOfObjects.filter(obj => {
    if (obj['min']) {
        if (obj['amt'] > obj['min']) return true
    } else {
        return true
    }
}) 
0

Here is one solution i tried

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);
tuhin47
  • 5,172
  • 4
  • 19
  • 29