javascript 数组对象的筛选
使用filter,find方法通过筛选条件筛选数组对象中的元素
let arr = [ {code: '1', name: '苹果'}, {code: '2', name: '雪梨'}, {code: '3', name: '葡萄'}, {code: '4', name: '香蕉'}, {code: '5', name: '橙子'}, ] let searchCode = '3' let searchByFilter = arr.filter(item => item.code === searchCode) let searchByFind = arr.find(item => item.code === searchCode) console.log(searchTarget) // [{code: "3", name: "葡萄"}],查不到则返回 [] console.log(searchByFind) // {code: "3", name: "葡萄"}, 查不到则返回undefined
两个数组对象取共同的集合
let arr2 = [ {code: '1', name: '苹果'}, {code: '3', name: '葡萄'}, {code: '6', name: '西瓜'}, {code: '7', name: '荔枝'} ] let conmonArr = arr.filter(item => arr2.some(it => it.code === item.code)) console.log(conmonArr) // [ // {code: "1", name: "苹果"}, // {code: "3", name: "葡萄"} //]