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!!
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(" ")
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)
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(''))
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With