2019/4/26
1.数组对象查询
现在有数组arr如下,要求输入关键字查询所有符合的对象并以数组对象的形式返回
var arr = [{ id:'1', name:'小明', tel:'3996', hobby:'读书' },{ id:'2', name:'小红', tel:'2289', hobby:'打代码' },{ id:'3', name:'小黑', tel:'666', hobby:'打代码' }]
输入关键字 3 则返回
[{ id:'1', name:'小明', tel:'3996', hobby:'读书' },{ id:'3', name:'小黑', tel:'666', hobby:'打代码' }]
输入关键字 ‘读书’ 则返回
[{ id:'2', name:'小红', tel:'2289', hobby:'打代码' }]
答案如下
var arr = [{ id:'1', name:'小明', tel:'3996', hobby:'读书' },{ id:'2', name:'小红', tel:'2289', hobby:'打代码' },{ id:'3', name:'小黑', tel:'666', hobby:'打代码' }] var newArr = arr.filter(item=>{ var tempItem = JSON.stringify(item) if (tempItem.indexOf('读书') !== -1) return item }) console.log(newArr) //[{id:'1',name:'小明',tel:'3996',hobby:'读书'}] }