0

I have an object array that looks just about like this

 var o = [
   {
    module : "mod1",
    customUrl : [
        { "state"    : "name1",
          "options"  : ["option1", "option2", "option3"]
        },
        { "state"    : "name2",
          "options"  : ["option1", "option2", "option3"]
        }
    ]
  },
 {
    module : "mod2",
    customUrl : [
        { "state"    : "name1",
          "options"  : ["option1", "option2", "option3"]
        },
        { "state"    : "name2",
          "options"  : ["option1", "option2", "option3"]
        }
    ]
 }
]

and in a function I a passed a string. I want to be able to check that string against the "module" keys and see if it matches any of them so like

 checkName = function(name) {
      //check if "name" matches any "module" in o

 }

Is this possible (I am using underscore but normal javascript is fine too).Thanks!

3 Answers 3

2

You can use function some, like so

var checkName = function(name) {
  return _.some(o, function (el) {
    return el.module === name;
  });
};

or some from Array

var checkName = function(name) {
  return o.some(function (el) {
    return el.module === name;
  });
};

Example

Sign up to request clarification or add additional context in comments.

Comments

1

Pure Javascript solution. This function returns false if the module name is not found or the position in the array when the name is found. This function does not count in duplicates, it only will give the position from the last match.

JSfiddle demo

var checkName = function(name) {
    var flag=false;
    for(var i=0; i<o.length;i++){
        if(name === o[i].module){
            flag=i;
        }
    }return flag;
};
console.log(checkName("mod2"));

Comments

1

Quite another way to do so wiit pure, native JavaScript: convert the object to string and check for exact module-part.

var checkName = function(haystack, needle) {
  return JSON.stringify(haystack).contains('"module":"' + needle + '"')
}

checkName(o, 'mod1'); // returns true
checkName(o, 'mod4'); // returns false

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.