0

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.

2
  • 2
    Hum... where's the array ? Commented Jun 11, 2013 at 16:17
  • 1
    Note that you should probably write criteriaArray as ['DB More Than 1','MM Equal 0'] Commented Jun 11, 2013 at 16:20

2 Answers 2

2

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'};
Sign up to request clarification or add additional context in comments.

1 Comment

This answer works! I used it to test my script initially and to catch some other bugs (some spacing issue), but eventually use dystroy's solution because it seems more elegant, as what you said. But for those who use dystroy's solution, please read my comment below.
0

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

4 Comments

I like the indexOf better than my nested loop; more elegant.
@prothid note that my solution doesn't work on IE8 without a shim. Yours works on IE8 ;)
somehow 'for (var key = allObj)' result in error 'missing ; after for-loop initializer'. Changing it to 'for (var key in allObj)' solve the problem. I used your solution for my script. Thanks a lot.
@user2475327 Sorry for the = in place of in. That was a typo.

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.