Ad

Error Cannot Read Property Name Fieldnamefilter Of Undefined When Filter Data?

I work on angular 7 app I face error cannot read property name 'fieldnamefilter' of undefined when filter data ?

filter name I get it dynamically based on variable fieldnamefilter

below code is give error on this.fieldnamefilter :

  contentBody:any[];
 fieldnamefilter:any;

console.log("data values : " + this.fieldnamefilter ) 
//result is data values : onlineURL on console log

// error display on line below filter data[0].this.fieldnamefilter
this.contentBody = data.filter(item =>item != data[0].this.fieldnamefilter);

but if i use it as data[0].onlineURL as below it working ;

 //working when use field name direct data[0].onlineURL

this.contentBody = data.filter(item =>item != data[0].onlineURL);

data is have datatype any[]; so How to solve this issue ;

Updated post I try :

console.log(this.fieldnamefilter it give me onlineURL
console.log(data[0][this.fieldnamefilter] it give me N/A
Ad

Answer

const data = [{onlineurl: 'asdasd'}, {onlineurl: 'xxxx'}];
const fieldnamefilter = 'onlineurl';
const filteredData = data.filter(entry => entry[fieldnamefilter] === data[0][fieldnamefilter]);

This snippet works as intended, so as we can not debug the code without a MRE, I can not tell anything further. If you providea a MRE in Stackblitz or somewhere, we can help further. Also if your data look different than this please provide a sample.

Ad
source: stackoverflow.com
Ad