如何使用数组过滤javascript对象?例如,我有一个名为arr1
的数组:
arr1 = [
{"id":"A0001", "user":"asdf"},
{"id":"A0002", "user":"fgh"},
{"id":"A0122", "user":"fegr"},
{"id":"B0003","user":"dff"},
{"id":"B1567", "user":"asdf"},
{"id":"C0012", "user":"dwdw"}
]
然后我用arr2 = ['A0', 'B0', 'A00']
我尝试使用filter和indexOf。
arr2.forEach(element =>{
console.log(arr1.filter(function(el){
return el.id.indexOf(element) !== -1
}))
})
它应该返回:
[
{"id":"A0001", "user":"asdf"},
{"id": "A0002", "user":"fgh"},
{"id":"A0122", "user":"fegr"},
{"id": "B0003","user":"dff"}
]
但是它返回:
[
{id:'A0001', user:'asdf' },
{id:'A0002', user:'fgh' },
{id:'A0122', user:'fegr' }
]
[
{id:'B0003', user:'dff' } ]
[
{id:'A0001', user:'asdf' },
{id:'A0002', user:'fgh' }
]