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)
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.
array.filter always return array. But you can try this-
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:So your code looks like this: