1

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?

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.