Random I.T
Random I.T

Reputation: 131

Cannot obtain value after filter() in Javascript

I want to obtain the value of a filtered array. In debugger, it shows I can find the value in the array, which return only one result, which is desired, after I assigned to another value I got undefined, why is that ? I have been using it the same way before.

let originalpost = raw.filter(a => a.id == id); // one record shown
let topic = originalpost.title;// undefine

previously I done this

  let data = raw.filter(a => a.ParentItemID == id);// an array of records retrieved

// later I can use its data....
// e.g. data.title ....

Upvotes: 0

Views: 33

Answers (2)

Random I.T
Random I.T

Reputation: 131

.filter returns results in an array, so one result means array starts from 0 thus

let originalpost = raw.filter(a => a.id == id); // one record shown
let topic = originalpost[0].title;// undefine

Upvotes: 0

Ricardo Rocha
Ricardo Rocha

Reputation: 16216

Filter will always get you an array of objects. For getting only one value you should use Find.

Follows an example:

const values = [
    {id:1, name:"first"},
    {id:2, name:"second"}
];

console.log(values.filter(element => element.id === 2));
console.log(values.find(element => element.id === 2));

Upvotes: 1

Related Questions