2

Is there a way to filter an array of objects by a particular value that could be in any property?

Let's say I have this object:

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

With Array.prototype.filter I might do

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

However this would return only one out of the two objects that have "two" as a value in any of their properties.

Whereas

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;
}

does the job, but is a brute force approach. Is there a better way to achieve the same result?

0

3 Answers 3

5
var arrOfObj = []; // objects you're sifting
var prop = 'whatever';

var matches = arrOfObj.filter(obj => Object.keys(obj).some(k => obj[k] === prop));

You want a combination of Array.prototype.filter and Array.prototype.some which returns a boolean if any of the elements of the array match the condition, it also stops iterating the array (in this case the keys of each object) as soon as it finds a match. If you need cross-browser support (and for some reason aren't using babel) the ES 5 version of the above is

var arrOfObj = []; // objects you're sifting
var prop = 'whatever';

var matches = arrOfObj.filter(function(obj) { 
  return Object.keys(obj).some(function(k) { 
    return obj[k] === prop; 
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Maybe include an ES5 version, to match the OP's code.
3

Well the obvious thing is to combine your for..in loop with your .filter() function:

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

var filtered = x.filter(function(v) {
  for (var k in v)
    if (v[k] === "two") return true;
});
console.log(filtered);

Comments

3

use an inner loop method to check individual property values

var val ="one";
var res = x.filter(function(item){
     return Object.keys(item).some(function(prop){
         return item[prop] === val;
     });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.