将字符串中的函数参数转换为对象中的参数 [英] Convert function parameter in string into parameter in object
本文介绍了将字符串中的函数参数转换为对象中的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用node.js.
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);
它没有用.使用str_param
调用add_row
的好方法是什么?
It did not work. What is a good way to use str_param
to call add_row
?
推荐答案
您可以将字符串转换为函数接受的对象.
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" }
这篇关于将字符串中的函数参数转换为对象中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文