user2475327
user2475327

Reputation: 3

jquery - filter multidimensional array

I have a multidimensional array like this:

var allObj = {'@DB M-T 1@': 'DB More Than 1','@ES L-T 5@': 'ES Less Than 5','@MM E-Q 0@': 'MM Equal 0'};

and I have a criteria like this:

var criteriaArray = {'DB More Than 1','MM Equal 0'};

I would like to create a new array out of the allObj array, such that it meets the values in criteriaArray. The output should look like this:

var matchObj = {'@DB M-T 1@': 'DB More Than 1','@MM E-Q 0@': 'MM Equal 0'};

From what I gather, I can use jquery grep. But I can't figure out how to do it correctly. I would appreciate if someone can help me. I've been on this for hours.

Upvotes: 0

Views: 1246

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382150

You seem to want to filter the properties of an object (not an array) by their values.

The simplest would be to do this :

var criteriaArray = ['DB More Than 1','MM Equal 0']; // your syntax was bad
var matchObj = {}; // resulting object
for (var key in allObj) {
   if (criteriaArray.indexOf(allObj[key]) !== -1) {
       matchObj[key] = allObj[key]
   }
}

Upvotes: 0

prothid
prothid

Reputation: 606

Here is an iterative solution:

var allObj = {'@DB M-T 1@': 'DB More Than 1','@ES L-T 5@': 'ES Less Than 5','@MM E-Q 0@': 'MM Equal 0'};
var criteriaArray = ['DB More Than 1','MM Equal 0'];
var matchObj = {};
for(var key in allObj) {
  var value = allObj[key];
  for(var i=0; i<criteriaArray.length; i++) {
    var criteria = criteriaArray[i];
    if(value==criteria) {
      matchObj[key] = value;
      break;
    }
  }
}
console.log(matchObj);//{'@DB M-T 1@': 'DB More Than 1','@MM E-Q 0@': 'MM Equal 0'};

Upvotes: 2

Related Questions