-1

I'm trying to convert a js config to string, but i'm having a problem with the imported values.
Please check the desired output below.

Codesandbox Example
This is a follow-up question to this: Refactoring javascript string config

import { TEST } from "./config";

export default function App() {
  let configString = (() => {
    var configOptions = {
      message: TEST.Success
    };
  }).toString();

  configString = configString.slice(
    configString.indexOf("{") + 1,
    configString.lastIndexOf("}")
  );

  return <p>{configString}</p>;
}

OUTPUT:
var configOptions = { message: _config.TEST.Success };

DESIRED OUTPUT:
var configOptions = { message: Success };

Cristian Muscalu
  • 9,007
  • 12
  • 44
  • 76

1 Answers1

1

Instead of casting everything into a string and then do (rather complex) transformations on that string, I'd suggest to convert the configuration keys and values into a string and add the { and } afterwards:

import { TEST } from "./config";


function objToString(obj) {
  // creates a string in the format 'key: value, key2: value2, etc...'
  return Object.entries(obj).reduce(
    (cstring, [key, value]) => {
      return cstring !== ''
        ? `${cstring}, ${key}: ${value}`
        : `${key}: ${value}`
    },
    ''
  );
}


export default function App() {
  const variable = "w00t";

  let configString = objToString({
    enableProp: true,
    style: "plain",
    onReady: function () {
      return true;
    },
    message: TEST.Success,
    variable
  });

  console.log(configString);

  return (<p>{`{${configString}}`}</p>); // <-- note the added {} to the front/end
}
David
  • 3,552
  • 1
  • 13
  • 24