简体   繁体   中英

Creating custom object from array

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
    }

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

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

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