6

I have a function that should take as an argument of the object and return a string

The code I wrote.

function check(obj) {
  return obj.toString();
}
3
  • 4
    JSON.stringify(object) --> BOOM ! -> you got a string Commented May 31, 2019 at 16:50
  • Not working this way. I tried.
    – user11580667
    Commented May 31, 2019 at 16:51
  • Yeah because JSON is encoded with double quotes around each property name and value if it's a string. So you would have to check actual.includes('"name": "Ant", "age": 28,.. etc)
    – James
    Commented May 31, 2019 at 20:27

6 Answers 6

11

If your object is like

const obj = { name: "John", age: 30, city: "New York" };

Use the JavaScript function JSON.stringify() to convert it into a string. Like this JSON.stringify(obj). then you will get this string:

"{"name":"John","age":30,"city":"New York"}"

1
  • How is this not marked as the answer? Commented Aug 13, 2024 at 19:22
9

let toString = ({name, age, language}) => `name: ${name}, age: ${age}, language: ${language}`;

const david = { name: 'David', age: 22, language: 'PHP' };

console.log(toString(david));

If you'd like to be more generic:

let toString = obj => Object.entries(obj).map(([k, v]) => `${k}: ${v}`).join(', ');

const david = { name: 'David', age: 22, language: 'PHP', favoriteFood: 'blue' };

console.log(toString(david));

2
  • Thanks. All 3 test passed but I got error "returns a whole string with all of the user's details". can u please help me?
    – user11580667
    Commented May 31, 2019 at 17:01
  • You'll need to provide more details. You should also look into how to debug code.
    – junvar
    Commented May 31, 2019 at 17:16
1

Apply this technique if you want to convert an object to a string without applying the JSON.stringify() function

let obj = { 
  x: 1, 
  y: 'HelloWorld',
  toString: function(){
    return `${this.x}, ${this.y}`;
  }
};

let result = String(obj);

console.log(result, 'type --> ', typeof result);

1

1% of the time, you might need something besides json. Almost always you need json, but...

Sometimes you need a JavaScript string, not json. Like when you're filling in a graphql template.

It's just like the json string, but it doesn't have quotes around the attributes.

export const toJavascriptString =
  (obj: any) => JSON.stringify(obj).replace(/\"([\w_-]+?)\"\:/g, '$1:')


var obj = {a: 'wsd', b: 2}
var str = JSON.stringify(obj).replace(/\"([\w_-]+?)\"\:/g, '$1:')
console.log(str)

{a:"wsd",b:2}

1
  • This is a good solution. But in a javascript Object you can't have a kebab-case key, unless it's in quotes. So if someone is looking to display an Object in a js syntax highlighter, just remove the dash from the char class, i.e.: [\w_] and you're good to go. (Also format with tabs using something like stringify(obj, null, 4))
    – countzero
    Commented Aug 31, 2024 at 5:47
1
function check(obj) {
  console.log(typeof obj) // object
  let res = JSON.stringify(obj)
  console.log(typeof res) // string
  return res;
}
let example = {name: "John"}
console.log(check(example)) // {"name":"John"}
1
var data = {name: "john", age: 30}
var str = JSON.stringify(data)  // "{\"name\":\"john\",\"age\":30}"
var btoas = btoa(str)  // "eyJuYW1lIjoiam9obiIsImFnZSI6MzB9"
var atobs = atob(btoas)  // "{\"name\":\"john\",\"age\":30}"
var myRealData = JSON.parse(atobs)  //{name: "john", age: 30}

` BOYAA !! `
3
  • it's just for testing string values. sometimes object code is changed to btoa can work when changed to atob the value is [Object object] Commented Aug 9, 2021 at 7:05
  • atob and btoa are available in the browser as are the alert codes. Commented Apr 17, 2023 at 1:10
  • object to string is needed, for example to store browser cookies. code works when using btoa(JSON.stringify(code)) Commented Apr 17, 2023 at 1:13