7

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
  • 5
    JSON.stringify(object) --> BOOM ! -> you got a string Commented May 31, 2019 at 16:50
  • Not working this way. I tried. 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) Commented May 31, 2019 at 20:27

6 Answers 6

12

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

Sign up to request clarification or add additional context in comments.

1 Comment

How is this not marked as the answer?
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 Comments

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?
You'll need to provide more details. You should also look into how to debug code.
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);

Comments

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 Comment

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

Comments

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 Comments

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]
atob and btoa are available in the browser as are the alert codes.
object to string is needed, for example to store browser cookies. code works when using btoa(JSON.stringify(code))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.