skip to Main Content

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?

2

Answers


  1. function stringFromObject(obj) {
      return Object.entries(obj)
        .map(([k, v]) => `${k} = ${v}`)
        .join(', ')
    }
    
    console.log(stringFromObject({ a: 1, b: 2 }))
    Login or Signup to reply.
  2. 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} 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search