dimanche 24 juillet 2016

Filtering array of objects based on value

Is there any better way , or trick with array.filter how to return an object that contains certain value?

Lets say i have an object

var x = [{
  name: "one",
  swp: "two"
}, {
  name: "two",
  swp: "three"
}, {
  name: "aa",
  swp: "bb"
}];

and i want to return all object that contains as value , it does not matter what property holds that value. With array.filter i would have to specify e.g

x.filter(function(y){ return y.name == "two" })

this would return only one out of two objects that has "two" as value of any of their propery.

function findValue( value ) {
  var y = [];
  for (obj in x) {
    for (val in x[obj]) {
      if (x[obj][val].match( value )) {
       y.push(x[obj]);
      }
    }
  }
  return y;
}

this does the job but its brute force. Is there any better way how to achieve same result?

Aucun commentaire:

Enregistrer un commentaire