Lit Aiy Lit Aiy - 1 year ago 44
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;


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

Answer Source

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" }