我想知道如何通过嵌套数组对象中的属性删除对象
我在sampleobj
中有完整的对象列表,将每个id与apitrans,apifund
进行比较,如果成功为假,则删除sampleobj中的obj
如果成功为 false,则删除 Sampleobj 中的对象。
我已经尝试过:
var result = sampleobj.foreach(e=>{
if(e.id === "trans" && apitrans.success== true){
Object.assign(e, apitrans);
}
if(e.id === "fund" && apifund.success== true){
Object.assign(e, apifund);
}
// if success false remove the object.
})
//inputs scenario 1
var sampleobj=[{
id: "trans",
amount: "100",
fee: 2
},
{
id: "fund",
amount: "200",
fee: 2
}]
var apitrans =
{
success: true,
id: "trans",
tamount: "2000",
fee: "12"
}
var apifund =
{
success: false,
id: "fund",
tamount: "4000",
fee: "10"
}
//inputs scenario 2 how to do same if property name differs
if error, status error, or success false remove obj in sampleobj
var sampleobj=[{
id: "trans",
amount: "100",
fee: 2
},
{
id: "fund",
amount: "200",
fee: 2
},
{ id: "insta", amount: "400", fee: 2 }
]
var apitrans = {success: true,id: "trans",tamount: "2000",fee: "12"}
var apiinsta = { errors: [{code:"error.route.not.supported"}],id: "insta",tamount: "2000",fee: "12"}
var apifund = { status: "error", id: "fund", tamount: "4000", fee: "10" }
var sampleobj=[{
//Expected Output
result: [
{
id: "trans",
amount: "100",
fee: 2
}
]```
最佳答案
您可以使用filter()
从数组中删除元素。
- 创建一个辅助函数 (
func
),它将两个对象作为参数,比较两个对象的id
属性,并检查其中一个对象的success
属性他们。 - 然后使用给定数组的
filter()
并将两个给定对象数组放入[apitrans,apifund]
。 - 然后在
[apitrans,apifund]
上使用some()
方法,并使用 Helper 检查其中任何一个的id
是否等于当前元素功能。
var arr=[ { id: "trans", amount: "100", fee: 2 }, { id: "fund", amount: "200", fee: 2 } ]
var apitrans = {success: true,id: "trans",tamount: "2000",fee: "12"}
var apifund = { success: false, id: "fund", tamount: "4000", fee: "10" }
const func = (obj1,obj2) => obj1.id === obj2.id && obj2.success
const res = arr.filter(x => [apitrans,apifund].some(a => func(x,a)));
console.log(res)
关于javascript - 如何在javascript中通过属性删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55963429/