Home > Software design >  function for making a string out of an object
function for making a string out of an object

Time:11-05

I need to make a function that generates a string from an object's key/value pairs. The string should be : "key = value, key = value". with spacing around the = and each key/value pair separated by a comma and space except for the last one.

So {a: "1'", b: "2"} would be "a = 1, b = 2".

I'm trying to learn so don't give me the code straight up, I mostly need to know where I'm wrong and guided to find the right answer. i currently have :

   function stringFromObject(obj) {
    obj = {};
    let key = (Object.keys(obj));
    let val = (Object.values(obj));
    str = (`${key} = ${val}, `)
    console.log(str)
}

when i console.log it i get :

 = ,
 = , 

why are keys and values not showing up correctly?

CodePudding user response:

Because you asked for a guidance and not the answer straight up:

One way to do this is using the native stringify function. In JavaScript an object can be stringified as if it was a JSON string, with JSON.stringify() static method. For example the {a: 1, b: 2} object stringifies as {"a":1,"b":2}.

Now that you got that string at hand, you can use any number of string modifier functions on it to format it to your desired way. For example you can replace : with = (including whitespaces) like:

function stringFromObject(obj) {
    let string = JSON.stringify(obj);
    // {"a":1,"b":2}
    string = string.replaceAll(":", " = ");
    // {"a" = 1, "b" = 2}
    //...
}

I guess you can now figure the whole thing out, right? You can carry on replacing until you get your desired format.

    string = string.replaceAll(":", " = ").replaceAll("\"", "");
    // {a = 1,b = 2}
    //...

If you are familiar with Regex, you can probably do the whole set of changes in one or two steps.

Another way could be looping through the key-value pairs. It works well for flat objects (where there are no nested objects) or you will need to recursively go through them. That would be a bit painful and unnecessarily slower way in case of large, nested objects, considering the speed and convenience the native functionality offers.

The main issue with your solution is that you replace the incoming object with an empty object, so nothing will be printed because there is nothing to be printed. The other issue is that Object.keys and Object.values each return an array (not a string) even if there is one key to show it will be an array of one member, so you should get the arrays member. Lastly, even if you fix those issues the current function only works for one pair (unless you call this function from within another loop).

CodePudding user response:

function stringFromObject(obj) {
  return Object.entries(obj)
    .map(([k, v]) => `${k} = ${v}`)
    .join(', ')
}

console.log(stringFromObject({ a: 1, b: 2 }))

  • Related