I would like to know how to remove the object based on condition using javascript
if the trans cost is > 200
, only have in obj
else remove it
var obj1 = [{
"id": "trans",
"option": "bank",
"cost": "100"
}, {
"id": "fund",
"option": "credit",
"cost": "300"
}, {
"id": "service",
"option": "bank",
"cost": "200"
}]
var obj2 = [{
"id": "trans",
"option": "bank",
"cost": "200"
}, {
"id": "fund",
"option": "credit",
"cost": "300"
}, {
"id": "service",
"option": "bank",
"cost": "200"
}]
//not working for obj2 returns []
function getData(obj) {
return obj.filter(i => i.id !== "trans" && i.cost < 200).map(e => e.id);
}
var result = getData(obj1); //output: ["fund","service"]
var result = getData(obj2); //output: ["trans","fund","service"]
Just try filter with 2 conditions , it worked for me .
var obj1 = [{ "id": "trans", "option": "bank", "cost": "100" }, { "id": "fund", "option": "credit", "cost": "300" }, { "id": "service", "option": "bank", "cost": "200" }] var obj2 = [{ "id": "trans", "option": "bank", "cost": "200" }, { "id": "fund", "option": "credit", "cost": "300" }, { "id": "service", "option": "bank", "cost": "200" }] let x1= obj1.filter(o=>o.id==="trans" && o.cost>=200); let x2= obj2.filter(o=>o.id==="trans" && o.cost>=200); console.log(x1); console.log(x2);
let filteredArray = obj1.filter(function(value){
return id === 'trans' && value.cost > 200;
});
You can do like this. The filteredArray will only contain values > 200
obj1.filter((transaction) => id === 'trans' && transaction.cost >= 200 );
obj2.filter(function(transaction){
return id === 'trans' && transaction.cost >= 200;
});
var obj1 = [{
"id": "trans",
"option": "bank",
"cost": "100"
}, {
"id": "fund",
"option": "credit",
"cost": "300"
}, {
"id": "service",
"option": "bank",
"cost": "200"
}]
var obj2 = [{
"id": "trans",
"option": "bank",
"cost": "200"
}, {
"id": "fund",
"option": "credit",
"cost": "300"
}, {
"id": "service",
"option": "bank",
"cost": "200"
}]
var obj1_filter = obj1.filter(function(options_list){
return options_list.id="trans" && options_list.cost>=200;
});
var obj2_filter = obj2.filter(function(options_list){
return options_list.id='trans' && options_list.cost>=200
});
console.log(obj1_filter);
console.log(obj2_filter);
It's will help you
使用以下filter
-
var result = obj1.filter(item => item.id === "trans" && item.cost > 200);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.