Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert object into string in javascript?

Tags:

javascript

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();
}

2 Answers

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"}"

like image 99
Hasibul- Avatar answered Jul 17 '26 23:07

Hasibul-


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));
like image 43
junvar Avatar answered Jul 18 '26 00:07

junvar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!