js filter过滤出符合条件的数组 但是要返回对象
时间: 2023-10-10 20:06:05 浏览: 39
可以使用 Array.prototype.reduce() 方法来将符合条件的数组转换成对象。下面是一个示例代码:
```javascript
const arr = [
{ name: 'Alice', age: 20 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 40 },
{ name: 'Dave', age: 50 },
];
const filteredObj = arr.reduce((obj, item) => {
if (item.age > 30) {
obj[item.name] = item.age;
}
return obj;
}, {});
console.log(filteredObj); // { Charlie: 40, Dave: 50 }
```
在上面的代码中,我们使用 reduce() 方法将符合条件的数组转换成对象。reduce() 方法接收两个参数:一个回调函数和一个初始值。回调函数接收两个参数:累加器和当前元素。在每次迭代中,我们检查当前元素是否符合条件,如果符合则将其添加到累加器中。最终,reduce() 方法返回累加器,即转换后的对象。
相关问题
前端的filter数组过滤返回符合条件的数组对象
好的,那么对于前端的数组过滤,可以使用 JavaScript 中的 filter() 方法来实现。filter() 方法会返回一个新的数组,其中包含符合指定条件的所有元素。
下面是一个例子,假设我们有一个数组,其中包含多个对象,每个对象都有一个 name 属性和一个 age 属性。现在我们想过滤出年龄大于等于 18 的所有对象:
```javascript
const persons = [
{ name: '张三', age: 20 },
{ name: '李四', age: 16 },
{ name: '王五', age: 25 },
{ name: '赵六', age: 30 }
];
const adults = persons.filter(person => person.age >= 18);
console.log(adults);
// 输出:[{ name: '张三', age: 20 }, { name: '王五', age: 25 }, { name: '赵六', age: 30 }]
```
在上面的代码中,我们使用了 filter() 方法,传入了一个箭头函数作为参数。这个箭头函数会判断每个元素的 age 属性是否大于等于 18,如果是,则保留该元素,否则过滤掉。
最终,filter() 方法返回了一个新的数组 adults,其中包含了符合条件的三个元素。
js filter过滤数组中对象
你可以使用 JavaScript 的 `filter()` 方法来过滤数组中的对象。`filter()` 方法接受一个回调函数作为参数,该回调函数会针对数组中的每个元素进行执行。在回调函数中,你可以编写过滤条件,只有满足条件的元素才会被保留在过滤后的数组中。
以下是一个示例,展示如何使用 `filter()` 方法来过滤数组中的对象:
```javascript
const array = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Bob' },
{ id: 4, name: 'Alice' }
];
// 过滤出名称为 'John' 的对象
const filteredArray = array.filter(obj => obj.name === 'John');
console.log(filteredArray);
// 输出: [{ id: 1, name: 'John' }]
```
在上述示例中,我们定义了一个包含多个对象的数组 `array`。然后,我们使用 `filter()` 方法来过滤出名称为 'John' 的对象,将其保留在 `filteredArray` 中。最后,我们打印输出 `filteredArray` ,得到了过滤后的结果。
你可以根据自己的需求修改回调函数中的过滤条件,来达到你想要的过滤效果。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)