[英]How to use spread operator to delete an object from array of objects using spread operator using react?
i want to delete an object from array of objects using spread operator.我想使用扩展运算符从对象数组中删除 object。
i have an array of objects like below,我有一个对象数组,如下所示,
const list= [
{
id: '1',
name: 'first_item',
},
{
id: '2',
name: 'second_item',
},
]
i can add another object say "next_item" like below我可以添加另一个 object 说“next_item”,如下所示
const next_item = {
id: '3',
name: 'next',
}
const final = [...list, next_item]
similary how can i delete delete_item from list同样,我如何从列表中删除 delete_item
const delete_item = {
id: '2',
name: 'second_item',
},
Could someone help me with this.有人可以帮我解决这个问题。 thanks.谢谢。
You can use filter您可以使用过滤器
list = list.filter(item => {
return item.id !=2;
})
Or can use a function like the below或者可以使用 function,如下所示
const removeFromList = (list, itemId) => {
return list.filter(item => {
return item.id != itemId;
});
}
There is no such thing with spread operator, but if you still want to force , here you go传播运算符没有这样的东西,但如果你仍然想强制,这里你 go
var arrayObj = [1,2,3,4,5,6] const index = arrayObj.findIndex(elm => elm === 5) const removed = [...arrayObj.slice(0,index), ...arrayObj.slice(index+1,arrayObj.length)] console.log(removed)
But there is no benefit of using it like this但是像这样使用它没有任何好处
You can use some of the destructuring features like this:您可以使用一些解构功能,如下所示:
var arrayObj = [1,2,3,4,5,6,7]; var [first, second, ...rest ] = arrayObj; console.log(first, second, rest);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.