gpt4 book ai didi

javascript - 如何在javascript中通过属性删除对象

转载 作者:行者123 更新时间:2023-12-02 23:43:24 24 4
gpt4 key购买 nike

我想知道如何通过嵌套数组对象中的属性删除对象

我在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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com