javascript - Filter things with changeable arguments -


let products = [ {     "name": "lenovo",     "price": "18000",     "model": "v580c" }, {     "name": "apple",     "price": "30000",     "model": "iphone 6" }, {     "name": "nikon",     "price": "25000",     "model": "g290" }] 

i need filter products array getproduct function, accepts changeable list of arguments. argument can either name of product and/or price within minprice, maxprice, and/or model.

function getproduct(productname, minprice, maxprice, productmodel) {      return products.filter(product => {         return product.price < maxprice && product.price > minprice && product.name == productname;     }); }  console.log(getproduct("apple", 3540, 3000000000)); console.log(getproduct("lenovo", 3540, 3000000000, "v580c")); 

you can send array of params argument , write logic process them accordingly.

sample:

function getproduct(array, params){    var list = array.filter(function(o){      return params.every(function(kv){        if(o.hasownproperty(kv.key)){          var cur = o[kv.key];          switch (kv.operation){            case ">":     return cur > kv.value             case "<":     return cur < kv.value             case "in":    return cur.indexof(kv.value) > -1            case "regex": return kv.value.test(cur)            default:      return cur === kv.value           }        }      })    });        console.log(list);    return list;  }    var products=[{name:"lenovo",price:"18000",model:"v580c"},{name:"apple",price:"30000",model:"iphone 6"},{name:"nikon",price:"25000",model:"g290"}];    getproduct(products, [{key:"name", value: "nikon"}])  getproduct(products, [    {key:"price", value: 20000, operation: ">"},    {key:"price", value: 40000, operation: "<"}  ])    getproduct(products, [{key:"name", value: "e", operation: "in"}])  getproduct(products, [{key:"model", value: /\d{2,}/g, operation: "regex"}])


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -