vue 对象数组根据id查找并删除
时间: 2023-06-04 15:03:29 浏览: 1081
可以通过以下代码实现:
```
let index = arr.findIndex(item => item.id === id);
if (index !== -1) {
arr.splice(index, 1);
}
```
其中,arr 为需要进行查找和删除的对象数组,id 为需要查找的 id 值,findIndex 方法会返回 id 值在数组中的下标,如果没找到则返回 -1。如果找到了,可以使用 splice 方法将该元素从数组中删除。
相关问题
Vue在数组对象中查找值并取出
在Vue中,可以使用`Array.prototype.find()`方法来查找数组中符合条件的对象,并取出该对象的值。与上面Javascript的方法类似,不同的是在Vue中通常会将数据存储在组件的`data`属性中,因此需要使用`this`关键字来获取数组对象。假设在Vue组件中有一个数组对象`list`,其中包含多个对象,每个对象有多个属性,可以使用以下方式来查找符合条件的对象,并取出该对象的值:
```
<template>
<div>
<ul>
<li v-for="item in list" :key="item.id">{{ item.name }} - {{ item.age }}</li>
</ul>
<p>{{ name }}</p>
</div>
</template>
<script>
export default {
data() {
return {
list: [
{ id: 1, name: "张三", age: 18 },
{ id: 2, name: "李四", age: 20 },
{ id: 3, name: "王五", age: 22 }
],
name: ""
}
},
mounted() {
// 查找年龄为20的对象,并取出该对象的姓名
var item = this.list.find(function(item) {
return item.age === 20;
});
this.name = item.name;
}
}
</script>
```
在上面的代码中,我们将数组对象`list`存储在组件的`data`属性中,使用`v-for`指令遍历数组对象并在页面中显示出来。在`mounted()`生命周期钩子中,使用`this.list.find()`方法查找年龄为20的对象,并将该对象赋值给变量`item`,最后使用`this.name`将该对象的`name`属性的值赋值给组件的`name`属性,用于在页面中显示出来。
vue找到数组id匹配的对象
可以使用JavaScript中的`find`方法来找到符合条件的数组元素。假设我们有一个数组`list`,其中每个元素都包含一个`id`属性,我们要查找`id`等于指定值的数组元素,可以这样做:
```javascript
let list = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
let targetId = 2;
let targetObj = list.find(item => item.id === targetId);
console.log(targetObj); // { id: 2, name: 'Bob' }
```
在上面的例子中,我们定义了一个`targetId`变量来存储要查找的`id`值,然后使用`find`方法来查找符合条件的数组元素。`find`方法接受一个回调函数作为参数,该回调函数会遍历数组中的每个元素,并返回第一个符合条件的元素。在回调函数中,我们使用箭头函数简写了一个匿名函数,它的参数`item`代表当前遍历到的元素,当`item.id === targetId`成立时,返回该元素。最后,用`targetObj`变量来存储查找到的数组元素。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)