Search code examples
javascriptarraysjavascript-objects

using join method on a value of object


I tried to join and add line break to my nested array using join and \n as you can see:

const exampleArray = [["Hello"], ["world"], ["example"]]
    .map((el) => el)
    .join("\n");

everything works. I get this output which is what I want:

Hello

world

example

but when I tried to add this exampleArray to a value inside of an object, it shows the \n itself instead of line break.

this is what I did:

const theObj = {
    value: exampleArray,
  };

and this is what I get in the output:

Object { value: "Hello\nworld\nexample" }

I want to have my text with line breaks in value. what is the problem and how can I solve it?


Solution

  • Here the problem is you are using objects where the data is stored in form of {key : string} and {value : <number | string | boolean >} form. You can not possibly store visual line-breaks in object-values. But if you print Object.value rather than Object itself it will print data in visual line breaks.

    const obj = {
      value : 'Hindi\nEnglish\nFrance'
    }
    console.log(obj)
    console.log(obj.value);
    
    
    /* first one will give o/p - {
      "value": "Hindi\nEnglish\nFrance"
    } */
    
    /* second one will give o/p 
    Hindi
    English
    France */