1. find(callback) find查詢出第一個(gè)符合條件的結(jié)果就會(huì)返回碴倾,返回是一個(gè)對(duì)象
1.基本查詢
const arrmock=[{name:'1',age:2},{name:'2'},{name:'1',age:'3'}]
const findname=arrmock.find(o=>o.name==='1')
console.log(findname); // { name: '1', age: 2 } 查詢出第一個(gè)符合條件不在往后查詢
2.嵌套查詢,查詢某一個(gè)子元素對(duì)應(yīng)的父元素的值(已知某個(gè)子元素中的key值穆咐,查詢父元素耕陷,再取出父元素key值)
const menuSlioder = [
{
key: '123123123',
title: '賬戶管理',
children: [
{
key: 'abcd',
title: '錢包賬戶',
},
],
},
{
key: 'sfwfsdf',
title: '賬戶管理',
children: [
{
key: 'abc',
title: '錢包賬戶',
},
{
key: 'abcde',
title: '賬戶流水明細(xì)',
},
],
},
];
const as = menuSlioder.find((item) => {
return Boolean(item.children.find((o) => o.key === 'abcd'));
});
// 等價(jià)于 some的用法依據(jù)判斷條件,數(shù)組的元素是否有一個(gè)滿足辙喂,若有一個(gè)滿足則返回ture捶牢,否則返回false
// const as = menuSlioder.find((item) => {
// return item.children.some((o) => o.key === 'abcd');
// });
console.log(as);
// {
// key: '123123123',
// title: '賬戶管理',
// children: [
// {
// key: 'abcd',
// title: '錢包賬戶',
// },
// ],
// }
2.filter(callback) 過濾數(shù)組,返回一個(gè)滿足要求的數(shù)組加派,callback是一個(gè)條件語句
1.基本用法
const users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false },
{ 'user': 'ared', 'age': 24, 'active': false },
{ 'user': 'ered', 'age': 80, 'active': false },
{ 'abc': 'ered', 'age': 80, 'active': false }
]
// 篩選 age等于40或者age等于24的 數(shù)組對(duì)象
const filtered = users.filter(n => n.age===40 || n.age===24)
console.log('filter后的鍵名', filtered) // => [{user: "fred", age: 40, active: false}叫确,{user: "ared", age: 24, active: false}]
const ac=users.filter(n => n.age===100)
console.log(ac); // []
2.數(shù)組中的空字符串刪除
const spread = ['A', '', 'B', null, undefined, 'C', ' ']
const filtered = spread.filter((item) => {
return item && item.trim()
})
console.log('數(shù)組中的空字符串刪掉', filtered) // => ["A", "B", "C"]
3.filter+map寫法用于剔除某些元素的騷操作
const arr = [
{
gender: 'man',
name: 'john',
},
{
gender: 'woman',
name: 'mark',
},
{
gender: 'man',
name: 'jerry',
},
];
// filter : 有條件的篩選,返回條件為true的數(shù)組
// 篩選出性別為男性的名字集合
const newArr = arr
.filter((n) => n.gender === 'man')
.map((item) => {
return {
name: item.name,
};
});
console.log('男性名字集合', newArr); // => [{name: 'john'}, {name: 'jerry'}]
4.在案例find中使用filter
const as = menuSlioder.filter((pro) => pro.children.some((o) => o.key === 'abcde'))
// => [ { key: 'sfwfsdf', title: '賬戶管理', children: [ [Object], [Object] ] } ]
menuSlioder.filter((pro) => pro.children.some((o) => o.key === 'abcde')).map((item)=>console.log(item))
// {
// key: 'sfwfsdf',
// title: '賬戶管理',
// children: [ { key: 'abc', title: '錢包賬戶' }, { key: 'abcde', title: '賬戶流水明細(xì)' } ]
// }