简体   繁体   中英

How to convert string to object to be able to pass that as a function parameters

I have this string "{ min: 1, max: 10, precision: 3 }"

I want to convert that just to be { min: 1, max: 10, precision: 3 } so I can pass that as an argument to some function faker.random.number({ min: 1, max: 10, precision: 3 })

How would you do the conversion in such case?

UPDATE: when I am using eval("faker.random.number({ min: 0, max: 10, precision: 1 })") I am getting error faker is not defined .

Short answer: eval.

Long answer: Don't use eval. Make your data in a standardized format (such as JSON) and use tools to parse said standardized format (such as JSON.parse() )

A lot of people are suggesting using the JSON.parse function, however it is not a valid json format. So it would simply return SYNTAX ERROR: Unexpected token a in JSON

What else comes to mind is using the eval function, but then again it would not work as the second parameter (2) isn't valid key in an object.

That being said we have to come up with some form of a transform function You can use splits to divide the function into separate parameters, and then use replace to remove the unnecesery spaces/brackets

var str = "{ a: 1, 2: 10, c: 3 }";
Object.assign({}, ...str.split(",").map(param => {
    param = param.replace("{", "").replace("}", "").split(":")
        .map(a=>a.replace(" ", ""));
    let object = {};
    object[param[0]]=param[1];
    return object;
}))
//returns {'2': 10, a: 1, c: 3}

after that assigning first part before the ":" to a key and the other part to the value is pretty straight forward. I then combine the smaller objects with one parameter each into a bigger one with object.assign.

You could use eval with something like:

faker.random.number(eval('void 0,' + '{ min: 1, max: 10, precision: 3 }'));

The 'void 0, part is necessary as if { is encountered as the first token in a statement, it's treated as the start of a block, not an object literal.

Anyway, you want to avoid eval so you'll have to parse the string manually. Hopefully it doesn't get too complex and you can keep it simple like the following, which can handle values that are strings or numbers but not much else:

 var s = '{ min: 1, max: 10, precision: 3 }'; function simpleParse(s) { // Remove unwanted characters, split into name:value pairs on , let parts = s.replace(/[ {}]/g,'').split(','); // Split properties on : and keep strings as strings, assume // anything else is a number return parts.reduce((acc, part) => { let [prop, value] = part.split(':'); acc[prop] = /[\\'\\"]/.test(value)? value : +value; return acc; }, Object.create(null)); } console.log(simpleParse(s)); 

You could convert the string to JSON, then use JSON.parse, but I don't see the point of parsing it twice. If the structure gets more complex, you'll need a more complex parser.

EDIT As mentioned below this is not valid JSON, so I like this puzzle :P My final solution:

var str = "{ a: 1, 2: 10, c: 3 }";
obj = str.replace(/[ {}]/g, "").split(",");
new_obj = {};
obj.forEach(function(element) {
    var t = element.split(':');
    new_obj[t[0]] = t[1];
});
console.log(new_obj);

This creates an array without making everything into a string.

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