ES6 filter - how to return an object instead of an

2020-07-09 03:03发布

问题:

I have bunch of array of object, I want to get particular object using filter, but I got array using below code.

const target = [{
  name: 'abc',
  id: 1
}, {
  name: 'def',
  id: 2
}]

const x = target.filter(o => o.id === 1)
console.log(x)

回答1:

As said in the comments, filter won't allow you to get a particular object from an array - it just returns another array which elements satisfy the given predicate. What you actually need is Array.prototype.find(). Quoting the doc:

The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

So your code looks like this:

const target = [{
  name: 'abc',
  id: 1
}, {
  name: 'def',
  id: 2
}];

const x = target.find(o => o.id === 1);
console.log(x); // {name: "abc", id: 1}



回答2:

array.filter always return array. But you can try this-

 const target = [{
      name: 'abc',
      id: 1
    }, {
      name: 'def',
      id: 2
    }]
   
let obj = {}    
const x = target.filter( (o, index) => {
  if(o.id === 1)
     obj = target[index]  
})
console.log(obj)



回答3:

Array.prototype.filter will return array containing elements from original array that passed test function.

If you are sure that id's are unique simply do x[0] to get result.