ajmajmajma
ajmajmajma

Reputation: 14226

Check if name exists in object array

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!

Upvotes: 0

Views: 78

Answers (3)

dsuess
dsuess

Reputation: 5347

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

Upvotes: 1

kasper Taeymans
kasper Taeymans

Reputation: 7026

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"));

Upvotes: 1

Oleksandr T.
Oleksandr T.

Reputation: 77522

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

Upvotes: 2

Related Questions