OneCompiler

[Javascript] How to convert an object to string?

I want to convert the below object to string

{
"name": "foo"
}

to

'{
"name": "foo"
}
'

How to do that in Javascript?

1 Answer

4 years ago by

You can covert an object to string as shown below in Javascript

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

let obj = { name: 'foo', id: 1 };

let str = toString(obj);

console.log(typeof(obj));
console.log(typeof(str));

Run here https://onecompiler.com/javascript/3xns6jwm4

4 years ago by Meera