0

The below code has a major flaw. The value type is changing. That is the value of "limit": 5 and "skip": 0 is converting to strings.

var arr = [
      'find({ qty: { $lt: 20 } } )',
      'limit(5)',
      'skip(0)'
    ]


var obj = {};

arr.forEach(function(x, n) {
  var m = x.match(/(\w+)\(\s*(.+?)\s*\)/);
  if(n == 0) {
    obj.action = m[1];
    obj.value = m[2];
  } else
    obj[m[1]] = m[2];

});

document.write("<pre>" + JSON.stringify(obj,0,3));

Expected output:

{
   "action": "find",
   "value": "{ qty: { $lt: 20 } }",
   "limit": 5,
   "skip": 0
}
3
  • I would presume you'd need to use a parseInt() on that specific string, otherwise it will interpret as a string. Commented Mar 31, 2015 at 13:55
  • 1
    You are handling strings and making regular expression matches. At no point will the values be considered anything other than strings. They are certainly not changing type. Commented Mar 31, 2015 at 13:57
  • 1
    This parses into limit: '5'. You need to make sure numbers are parsed as such. Commented Mar 31, 2015 at 13:58

2 Answers 2

1

Before assigning m[2] to a key in obj, check if it is a number. If so, parse it:

arr.forEach(function(x, n) {
  var m = x.match(/(\w+)\(\s*(.+?)\s*\)/);
    if(n == 0) {
      obj.action = m[1];
      obj.value = m[2];
    } else{
      var key = m[1], val = m[2];
      if (!isNaN(val)) {
          val = parseInt(val);
      }

      obj[key] = val;
  }
});

Try it in a fiddle.

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

2 Comments

This assumes the OP doesn't want decimal numbers as values.
I felt that was a safe assumption given the nature of the object. It appears to be a MongoDB query.
0

I'm not entirely sure what your code is trying to achieve, but you could try casting the values as Numbers before adding them to your object.

Like this:

arr.forEach(function(x, n) {
  var m = x.match(/(\w+)\(\s*(.+?)\s*\)/);
  if(n == 0) {
    obj.action = m[1];
    obj.value = !isNaN(m[2]) ? Number(m[2]) : m[2];
  } else
    obj[m[1]] = !isNaN(m[2]) ? Number(m[2]) : m[2];

});

Here's a CodePen.

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.