Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 filter - how to return an object instead of an array?

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)
like image 399
Jane Emelia Avatar asked Sep 13 '17 09:09

Jane Emelia


People also ask

Does filter return an object?

The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array. The filter() function loops or iterate over each array element and pass each element to the callback function.

Does filter always return an array?

filter always returns an array (array of all the filtered items), use array. find to get the single object. please change your title, because you get an array as result of filter .


2 Answers

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}
like image 90
raina77ow Avatar answered Sep 22 '22 19:09

raina77ow


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)
like image 45
Sahid Hossen Avatar answered Sep 22 '22 19:09

Sahid Hossen