Jane Emelia
Jane Emelia

Reputation: 497

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)

Upvotes: 24

Views: 31806

Answers (5)

M. Inam
M. Inam

Reputation: 329

It's very easy just get first item in retrned as:

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

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

Upvotes: -1

Fabio Valencio
Fabio Valencio

Reputation: 21

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

The find() method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

Upvotes: 2

Sahid Hossen
Sahid Hossen

Reputation: 1467

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)

Upvotes: 5

raina77ow
raina77ow

Reputation: 106453

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}

Upvotes: 65

przemo_li
przemo_li

Reputation: 4053

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.

Upvotes: 0

Related Questions