Request chapter XHR

CAN somoeone explain me what’s mean this function :



const formatJson = (resJson) => {
  resJson = JSON.stringify(resJson);
  let counter = 0;
  return resJson.split('')
  .map(char => {
    switch (char) {
      case ',':
        return `,\n${' '.repeat(counter * 2)}`;
      case '{':
        counter += 1;
        return `{\n${' '.repeat(counter * 2)}`;
      case '}':
        counter -= 1;
        return `\n${' '.repeat(counter * 2)}}`;
      default:
        return char;
    }
  })
  .join('');
}




That looks like a helper function that’s designed to return a formatted string so JSON is easier to read in the console. Most likely just to help illustrate the levels of the JSON during the lesson.

For example, calling that function with a variable containing:

{ "test": 5, "levels": { "another": 5, "deeper": { "another": "testing" } } }

would return the following string:

{
  "test":5,
  "levels":{
    "another":5,
    "deeper":{
      "another":"testing"
    }
  }
} 

but Json.stingify method is enough to accomplish to formate object to string.

They don’t have the same output. The helper function you posted adds the line-breaks and indentation to make it easier to read in the console.

JSON.stringify() would return:

{"test":5,"levels":{"another":5,"deeper":{"another":"testing"}

vs that formatJson() helper function you posted:

{
  "test":5,
  "levels":{
    "another":5,
    "deeper":{
      "another":"testing"
    }
  }
} 

Sir can you explain step by step please because when i try your code in example the result don’t execute like expected :
console.log({\n${' '.repeat(1)} I learn javascript since 5 months)
the console run like this :
“{
I learn javascript since 5 months”

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.