简体   繁体   中英

Get values from Key/Value variable in javascript

Please consider this scenario:

I have a Key/Value variable like this:

var dict = {"78": "X",
            "12": "G",
            "18": "R",
            "67": "U",
            "68": "O",
            "30": "P"}

I have a string that I want to check if there is a letter of my variable exist in my string. How I can do this?

Collect object key values and use them to create a regular expression. Then use .test(yourString) :

var myStr = "Group";
new RegExp(Object.keys(dict).map(function (c) { return dict[c]; }).join("|"))
   .test(myStr); // true

Another way is simply iterating the object:

var found = false;
for (var k in dict) {
   if (myStr.indexOf(dict[k]) !== -1) {
      found = true;
      break;
   }
}

if (found) {
   // letter found
}

One possible approach:

var contains = Object.keys(dict).some(function(key) {
  return someStr.indexOf(dict[key]) !== -1;
});

In other words, iterate over the collection, at each step checking whether or not the tested character present in your string ( someStr ). If it is, stops the iteration immediately (that's how Array.prototype.some works).

Another approach is building a character class regex, then using it against the string:

var pattern = RegExp('[' + Object.keys(dict).map(function(k) { 
  return dict[k]; 
}).join('') + ']');
var contains = pattern.test(someStr);

The second approach is slightly better if the tested strings usually do contain the characters from dict . It's also quite easy to augment this solution into case-insensitive search - just add 'i' string as a second param of RegExp call.

The caveat is that you'll have to escape the characters that will be considered meta within a string passed into RegExp constructor (backslash, for example). If there are no such characters in the dictionary, it's not a problem, though.

It can be done using the following:

str = "test"; 
isExists = false;
for(var key in dict){
  isExists = str.indexOf(dict[key]) !== -1;
  if(isExists)
    break;
};
console.log(isExists);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM