Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning an object to a string using native javascript

I have defined the following object:

let myObj = {
my: 'name',
is: 'Inigo Montoya',
prepare: 'to die!'
}

What is the best way of making myObj to equal { "my name is Inigo Montoya prepare to die!" }?

I know you can Stringify using JSON, but I'd like doing it in native Javascript. I've tried the following to get a string made of all the object properties + values:

let combined = Object.entries(obj).forEach(entire => {
  return `${entrie[0]} ${entrie[1]}` });

but I only get undefined.

I'd love understanding why I'm getting undefined in this particular case, and also hearing what would you say the best way to solve the problem described above. Thanks!!

like image 962
rzk666 Avatar asked Mar 11 '19 17:03

rzk666


4 Answers

You can't return from a forEach, rather map to an array of the returned paired strings, then join that to one string:

Object.entries(obj).map(entry => `${entry[0]} ${entry[1]}`).join(" ");

Or I'd just do

Object.entries(obj).flat().join(" ")
like image 177
Jonas Wilms Avatar answered Oct 09 '22 13:10

Jonas Wilms


forEach returns undefined. You can use Object.entries and reduce

let myObj = {my: 'name',is: 'Inigo Montoya',prepare: 'to die!'}

let string = Object.entries(myObj)
             .reduce((op,[key,value])=>op+= ' '+ key + ' '+ value, '')
             .trim()

console.log(string)
like image 36
Code Maniac Avatar answered Oct 09 '22 12:10

Code Maniac


Using the String constructor convert the object into a string and using split and join remove : and ,

let myObj = {
my: 'name',
is: 'Inigo Montoya',
prepare: 'to die!'
}
console.log(String(JSON.stringify(myObj)).split(':').join(" ").split(',').join(' ').split(`"`).join(''))
like image 1
ellipsis Avatar answered Oct 09 '22 12:10

ellipsis


let myObj = {
  my: 'name',
  is: 'Inigo Montoya',
  prepare: 'to die!'
}

const res = Object.entries(myObj).map(el => el[0].concat(" " + el[1])).join(" ")


console.log(res)
like image 1
G.aziz Avatar answered Oct 09 '22 13:10

G.aziz