1

How can I simplify the following better using Underscore? It feels like too much code for something very simple. It creates a regex from the object keys.

var obj = {
   'dog' : 1,
   'cat' : 1,
   'rat' : 1
};

var arr = [], regex;

_.each( obj, function( value, index ){
  arr.push( index );
});

regex = _.reduce( arr, function(){
  return new RegExp( arr.join('|'), 'i' );
});

// console.log( regex ) should output: 
/dog|cat|rat/i 

2 Answers 2

1

Simply use Object.keys and native Array.prototype.join like this

console.log(new RegExp(Object.keys(obj).join("|"), "i"));

With _, it will be _.keys

console.log(new RegExp(_.keys(obj).join("|"), "i"));

The result would be

/dog|cat|rat/i
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, I landed on the first one, but +1 for included the Underscore version.
0

I quickly figured that you don't need to use underscore for this.

 var regex = new RegExp( Object.keys( obj ).join('|'), 'i' );

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.