Javascript JS indexOf对象数组和splice()未删除正确的对象
我有一个这样的对象数组:Javascript JS indexOf对象数组和splice()未删除正确的对象,javascript,vue.js,ecmascript-6,vuejs2,vuex,Javascript,Vue.js,Ecmascript 6,Vuejs2,Vuex,我有一个这样的对象数组: "followers": [ { "id": "1be87842-2f7f-4e3b-8fde-9a998feb3a01", "bug_id": "4ae2707b-07ef-4e07-95da-77855c67fece", "user_id": "e9e81aa2-4994-483d-a3a7-3b88491f1fda", "username": "texa
"followers": [
{
"id": "1be87842-2f7f-4e3b-8fde-9a998feb3a01",
"bug_id": "4ae2707b-07ef-4e07-95da-77855c67fece",
"user_id": "e9e81aa2-4994-483d-a3a7-3b88491f1fda",
"username": "texample1",
"name": "Test Example1",
"created_at": "2018-11-27 21:01:42",
"updated_at": "2018-11-27 21:01:42",
"deleted_at": null
},
{
"id": "7bd1fa5f-4109-4beb-b53a-fb03a1d23536",
"bug_id": "4ae2707b-07ef-4e07-95da-77855c67fece",
"user_id": "e9e81aa2-4994-483d-a3a7-3b88491f1fda",
"username": "texample1",
"name": "Test Example2",
"created_at": "2018-11-27 21:01:48",
"updated_at": "2018-11-27 21:01:48",
"deleted_at": null
}
]
我正在尝试使用vuex存储中的以下代码通过索引删除一个对象:
let followersArray = state.bugs.find(b => b.id === follower.bug_id).followers
let index = followersArray.indexOf(follower)
followersArray.splice(index, 1)
我将一个完整的跟随者对象传递给这个变种,然后在bug对象上找到跟随者数组,找到索引并尝试将其从完整bug对象的跟随者对象数组中拼接。此代码将从错误中删除另一个跟随者。索引记录为-1,应该是1。有人看到我遗漏了什么吗?如果我能得到正确的索引,我还会在其中添加一个
If(index!=-1))
。当您运行此代码并返回-1
:
let index=followersArray.indexOf(follower)代码>
这意味着followersArray
中不包含followersArray
对象。followerArray
可能包含follower
对象的副本,而不是对同一对象的引用
即使follower
对象与followersArray[1]
中的对象具有相同的属性和属性值,索引将返回一个-1
,除非它们是完全相同的对象
现在,如果您只想在数组中查找具有匹配属性值的对象(例如id
),则可以使用map
或findIndex
执行此操作:
let index=followersArray.map(i=>i.id).indexOf(follower.id)代码>如果在控制台中打印FollowerArray的结果,它会显示什么?如果im-correct-find返回一个数组,即使它只是一个元素,也可以用这个
let followersArray = state.bugs.find(b => b.id === follower.bug_id).followers[0]
您可以使用findIndex()
函数并根据跟随者的id返回其索引:
let index = followersArray.findIndex(i => i.id === follower.id);
示例:
let项目=[{
名称:“aaa”
}, {
名称:“bbb”
}, {
名称:“ccc”
}];
设c={
名称:“ccc”
};
让index=items.findIndex(item=>item.name==c.name)
console.log(index)
如果您使用“followers”:{}
而不是“followers”:[]
您可以命名键,这将使索引抓取更简单。这是最简单的解决方案+1这奏效了。对象稍有不同,所以按id查找索引效果最好。谢谢@HusamIbrahim非常感谢,我不明白为什么有人会否决我的答案,如果我的答案出了问题,他可以在评论中提到