Reputation: 131
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
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
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