Convert function parameter in string into parameter in object

烈酒焚心 提交于 2019-12-24 17:50:02

问题


I am using node.js.

I have a function that can be called this way;

add_row({location:'L1', row_name:'r1', value:'18.4'});

I have a string like this;

var str_param = "location:'L1', row_name:'r1', value:'18.4'";

I tried to do something like this to keep my code simple;

add_row(str_param);

It did not work. What is a good way to use str_param to call add_row?


回答1:


You could convert the string to an object that the function accepts.

function toObj(str) {
  const a = str.split(/,.?/g);
  return a.reduce((p, c) => {
    const kv = c.replace(/'/g, '').split(':');
    p[kv[0]] = kv[1];
    return p;
  }, {});
}

toObj(str); // { location: "L1", row_name: "r1", value: "18.4" }

DEMO




回答2:


I think this may be your issue:

{location:'L1', row_name:'r1', value:'18.4'} // Object
var str_param = "location:'L1', row_name:'r1', value:'18.4'"; // Not object

var str_param = "{location:'L1', row_name:'r1', value:'18.4'}"; // Object String

I do not use Node JS but just taking a shot in dark. If not you could just make function like:

function addRow(pLocation, pRowName, pValue) {
    var row = {
        location: pLocation,
        row_name: pRowName,
        value: pValue
    }

    // Logic ....
}

If that does not work try using Object string and look at function ParseJSON I believe it's called.



来源:https://stackoverflow.com/questions/37023792/convert-function-parameter-in-string-into-parameter-in-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!