去掉数组中的每条对象里嵌套的数组里不符合要求的数据
时间: 2024-02-03 21:15:29 浏览: 24
假设嵌套的数组是对象数组,可以通过使用 Array.prototype.map() 和 Array.prototype.filter() 方法来实现。
具体步骤如下:
1. 使用 map() 方法遍历原始数组,获取每个对象中嵌套的数组。
2. 使用 filter() 方法过滤掉嵌套数组中不符合要求的数据。
3. 用过滤后的数组替换掉原始数组中的嵌套数组。
以下是示例代码:
```javascript
const data = [
{
id: 1,
name: 'Alice',
hobbies: ['reading', 'swimming', 'dancing']
},
{
id: 2,
name: 'Bob',
hobbies: ['running', 'hiking', 'photography', 'gaming']
}
];
const filteredData = data.map(obj => {
const filteredHobbies = obj.hobbies.filter(hobby => {
return hobby.length <= 7; // 只保留长度小于等于7的兴趣爱好
});
return {...obj, hobbies: filteredHobbies};
});
console.log(filteredData);
// 输出:
// [
// {
// id: 1,
// name: 'Alice',
// hobbies: ['reading', 'swimming', 'dancing']
// },
// {
// id: 2,
// name: 'Bob',
// hobbies: ['running', 'hiking', 'gaming']
// }
// ]
```
在上面的代码中,我们过滤了长度小于等于7的兴趣爱好。你可以根据自己的需求修改过滤条件。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)