3

I have an array with below elements. I am trying to create an object from the array

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

Below is my code. where I am getting only values as the output. Any help on this will be helpful

for (var i = 0; i < arr.length; i++) {
        var res = arr[i].search(/\(/ig)
        if (res!= -1) {
            var result = arr[i].split("(");
            result = result[1].slice(0, -1))
        }
    }

Expected Output

 {
      "action": "find",
      "value": "{ qty: { $lt: 20 } }",
      "limit": 5,
      "skip": 0
    }

2 Answers 2

3

match is better than split for this kind of stuff

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

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

4 Comments

Thanks all for helping me. Now Im getting the expected output. Is it possible to make the value as Object not as string ({ qty: { $lt: 20 } }). { "action": "find", "value": "{ qty: { $lt: 20 } }", "limit": 5, "skip": 0 }
@mish Your code is working buthas one major flaw. { "action": "find", "value": "{ qty: { $lt: 20 } }", "limit": "5", "skip": "0" } Values are getting converted to string. Eg. "limit":5
@user4324324: I didn't answer - whose code are you referring to?
@mish My mistake. I apologize for it. :)
2

see this fiddle

Just check if element is first in array, if yes, set action and value keys to splitted array, else just assign splitted values to key and value respectively

var arr = [
  'find({ qty: { $lt: 20 } } )',
  'limit(5)',
  'skip(0)'
]
var result = {};
for (var i = 0; i < arr.length; i++) {
  var res = arr[i].split("(")
  console.log(res)
  result[res[0]] = res[1].split(')')[0]
}

document.write(JSON.stringify(result))

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.