如何在javascript中的嵌套数组对象中删除对象

时间:2019-08-06 04:12:34

标签: javascript jquery arrays object

我想知道如何根据条件使用javascript删除对象

如果trans cost is > 200仅存在于obj中,则将其删除

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"]

5 个答案:

答案 0 :(得分:0)

只需尝试使用2个条件的过滤器,它对我有用。

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);

答案 1 :(得分:0)

let filteredArray = obj1.filter(function(value){

    return id === 'trans' && value.cost > 200;
});

您可以这样做。 filterArray仅包含> 200

的值

答案 2 :(得分:0)

obj1.filter((transaction)=> id ==='trans'&& transaction.cost> = 200);

obj2.filter(function(transaction){

return id === 'trans' && transaction.cost >= 200;

});

答案 3 :(得分:0)

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);

它将为您提供帮助

答案 4 :(得分:0)

按如下所示使用filter-

var result = obj1.filter(item => item.id === "trans" && item.cost > 200);