定义一个对象数组obj
const obj = [
{
'id': '1',
'name': 'wer',
'age': 18
},{
'id': '2',
'name': 'success',
'age': 20
},{
'id': '3',
'name': 'fail',
'age': 17
}
]
1、取出obj其中的某几项属性,并生成新的key值,组成一个新的数组
const obj2 = obj.map(({name, age}) => ({lable: name, value: age}));
console.log(obj2);
输出
obj2 = [
{
'label': 'wer',
'value':18
},{
'label': 'success',
'value':20
}
]
2、获取obj中符合某个数组条件的项
const obj3 = ['1','2'];
const obj4 = obj.filter(({id}) => obj3.includes(id));
console.log(obj4, 'obj4');
输出
obj4=[
{
'id': '1',
'name': 'wer',
'age': 18
},{
'id': '2',
'name': 'success',
'age': 20
}
]
3、将数组中某个属性全部抽出,组成一个新的数组
const obj5 = obj.map(a => a.id);
console.log(obj5, 'obj5');
输出
obj5 = ["1", "2", "3"]
4、获取字符串的长度
const {length: len} = 'hello';
console.log(len, 'len');
输出
5
5、使用find找出第一个符合条件的数组成员
const obj6 = obj.find(({age}) => age > 15);
console.log(obj6, 'obj6');
输出(只输出第一个符合条件)
obj6 = [
{
'id': '1',
'name': 'wer',
'age': 18
}
]
因此find可以用于检测某个数组成员是否存在。