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));
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))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]atob and btoa are available in the browser as are the alert codes.btoa(JSON.stringify(code))
JSON.stringify(object)--> BOOM ! -> you got a stringactual.includes('"name": "Ant", "age": 28,.. etc)