Lit Aiy Lit Aiy - 7 months ago 12
Javascript Question

Convert function parameter in string into parameter in object

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
?

Answer

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

Comments