Search code examples
javascriptarraysreactjsfilterjavascript-objects

How to make Javascript filter value based on dynamic key


I have one record and need to filter it according to supplied key and keep to another array. So normally we do like this..

let date = [];
date.push(data.filter(e => e.date).map(e => e.date));

this will give me data of['2020-09-12','2020-09-12','2020-09-12','2020-09-12'] in new date array.So now I have requirement to filter out dynamic key to new array.It is based on Daily, Weekly, Monthly which will look like this..(doing manually right now..)

if user select daily data..

let newArray30, newArray20, newArray10= [];
newArray30.push(data.filter(e => e.d_dy_30).map(e => e.d_dy_30));
newArray20.push(data.filter(e => e.d_dy_20).map(e => e.d_dy_20));
newArray10.push(data.filter(e => e.d_dy_10).map(e => e.d_dy_10));

if user select weekly data..

let newArray30, newArray20, newArray10= [];
newArray30.push(data.filter(e => e.d_wk_30).map(e => e.d_wk_30));
newArray20.push(data.filter(e => e.d_wk_20).map(e => e.d_wk_20));
newArray10.push(data.filter(e => e.d_wk_10).map(e => e.d_wk_10));

if user select monthly data..

let newArray30, newArray20, newArray10= [];
newArray30.push(data.filter(e => e.d_mt_30).map(e => e.d_mt_30));
newArray20.push(data.filter(e => e.d_mt_20).map(e => e.d_mt_20));
newArray10.push(data.filter(e => e.d_mt_10).map(e => e.d_mt_10));

and I will have 10 lines of each 'daily, weekly, monthly,quarterly,yearly'

I want to make it dynamic like this..

n30Data.push(data.filter(e =>e.this.getNaming(period,code)).map(e =>e.this.getNaming(period,code)))
//ofcourse this is error



  getNaming(period, code){

    return 'd'_'+period+'_'+code+'';
    
  }

how can I achieve something like above?


Solution

  • This will filter the result based on dynamic filterName key:

    function getNaming(period, code){
    
        return 'd_' + period + '_' + code;
        
      }
    
    var filterName = getNaming(period,code);
    n30Data.push(data.filter(e => e[filterName]).map(e => e[filterName])