Boky Boky - 2 months ago 6
React JSX Question

Return an object with a function

I want to return an object with a function in React JS.

I have the next code :

let filters = [
{name: "PRICE_RANGE", values: [{active: "true", low: 10000, high: 21000}]}
]


getFilterValues(filters, filterName){
return filters.filter(f => {
if(f.name === filterName) {
return {low: f.values.low, high: f.values.high};
}
})
}



<PriceFilter values={this.getFilterValues(filters, "PRICE_RANGE")} />


The result that I get is

{name: "PRICE_RANGE", values: [{active: "true", low: 10000, high: 21000}]}


But I want something like this :

{low: 10000, high: 21000}


Any advice why I'm getting whole array back and not the object?

Answer

Hope this snippet will be useful.

Create a generic function which will accept the key which you want to filter. Create an object and populate it with low & high value if it matches. Return the object.

  let filters = [{
  name: "PRICE_RANGE",
  values: [{
    active: "true",
    low: 10000,
    high: 21000
  }]
}]

function filterMe(key){
 var newObj={};
   filters.filter(function(item,index) {
      if(item.name === key){
         newObj.low=item.values[0].low;
         newObj.high=item.values[0].high
       }
    })
    return newObj;
}
console.log(filterMe("PRICE_RANGE"))

JSFIDDLE

Comments