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();
}
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"}"
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));
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% 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}
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)
)
Commented
Aug 31, 2024 at 5:47
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"}
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 !! `
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
btoa(JSON.stringify(code))
Commented
Apr 17, 2023 at 1:13
JSON.stringify(object)
--> BOOM ! -> you got a stringactual.includes('"name": "Ant", "age": 28,.. etc)