Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }
like image 533
user4324324 Avatar asked Apr 15 '26 17:04

user4324324


2 Answers

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));
like image 59
georg Avatar answered Apr 17 '26 05:04

georg


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))
like image 43
Naeem Shaikh Avatar answered Apr 17 '26 06:04

Naeem Shaikh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!