如何在javascript中按属性删除对象
我想知道如何在嵌套数组对象中按属性删除对象 我在如何在javascript中按属性删除对象,javascript,jquery,arrays,object,Javascript,Jquery,Arrays,Object,我想知道如何在嵌套数组对象中按属性删除对象 我在sampleobj中有完整的对象列表,将每个id与apitrans、apifund进行比较,如果成功为false,则删除sampleobj中的对象 在sampleobj中,如果成功为false,则删除该对象 我试过: var result = sampleobj.foreach(e=>{ if(e.id === "trans" && apitrans.success== true){ Object.assig
sampleobj
中有完整的对象列表,将每个id与apitrans、apifund
进行比较,如果成功为false,则删除sampleobj中的对象
在sampleobj中,如果成功为false,则删除该对象
我试过:
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]
方法,并使用Helper函数检查其中是否有some()
等于当前元素id
var arr=[{id:“trans”,金额:“100”,费用:2},{id:“fund”,金额:“200”,费用:2}]
var apitrans={success:true,id:“trans”,tamount:“2000”,fee:“12”}
var apifund={success:false,id:“fund”,tamount:“4000”,fee:“10”}
常量func=(obj1,obj2)=>obj1.id==obj2.id&&obj2.success
const res=arr.filter(x=>[apitrans,apifund].some(a=>func(x,a));
console.log(res)
您可以根据条件筛选出您的数组,即筛选器将为您提供新数组,而不是更改原始数组
var-arr=[{
id:“trans”,
金额:“100”,
费用:2
},
{
id:“基金”,
金额:“200”,
费用:2
}
]
var apitrans={
成功:没错,
id:“trans”,
塔蒙特:“2000年”,
费用:“12”
}
var apifund={
成功:错,
id:“基金”,
塔蒙特:“4000”,
费用:“10”
}
var filter=arr.filter(功能(项目){
//控制台日志(项目);
if(item.id==apitrans.id&&apitrans.success){
退货项目
}
});
控制台日志(过滤器)
您可以使用filter
例如`const result=sampleobj.filter(o=>o.id===apitrans.id&&!apitrans.success)`。相应地改变上述条件。看更多你能解释更多吗。。?告诉我们你到目前为止尝试了什么,因为我没有得到你的问题你想比较sampleobj arr和两个obj。两个obj都有id,它们存在于一个数组中(id fund n id trans)@我已经更新了帖子,补充了我所拥有的tried@the_ultimate_developer我需要比较apitrans与sampleobj和apifund与sampleobj,如果成功为假,请删除sampleobj中的obj@sowmiya-yep了解并已发布我的答案谢谢,但如果属性不同怎么办,更新你的答案input@sowmiya你在问题中没有提到类似的事情。是的,道歉。我没有,但它的场景不同,@sowmiya你应该用完整的信息编辑这个问题。@sowmiyavar-apinsta={errors:[code:],id:“insta”,tamount:“2000”,fee:“12”}
是错误的,因为它包含带键的数组<代码>[code:”“]数组不能有key:value。