5

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!!

2
  • 2
    .forEach always returns undefined, you probably want .map() Commented Mar 11, 2019 at 17:58
  • forEach does not make any sense since return does nothing.... Commented Mar 11, 2019 at 17:59

6 Answers 6

8

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(" ")
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer and the clean solutions! marked it as the answer.
1

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)

Comments

1

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(''))

1 Comment

I literally said I know I can use JSON stringify but I want to do it with native Javascript only :|
1

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)

Comments

0

You can use reduce() because forEach() always returns undefined

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

let combined = Object.entries(myObj).reduce((ac,entrie)=> ac  + ` ${entrie[0]} ${entrie[1]} ` ,'').trim();;
  console.log(combined)

1 Comment

Don't know why it got downvoted but I upvoted this one. I liked the reduce approach a lot. Thanks!
0

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

var the_keys = Object.keys(myObj),
  length = the_keys.length,
  resArray = new Array(length);
  
while (length--) {
  resArray[length] = [the_keys[length], myObj[the_keys[length]]];
}
var myStr = resArray.join(" ").replace(/,/g, ' ');
console.log(myStr);

This answer will accommodate those who have an older browser that does not support Object.entries. The code sets three variables: the_keys assigned the result of passing myObj to Object.keys(), length gets assigned the length property of that array, resArray results from creating a new array, using the length variable to set it. Then the resArray is iteratively filled with an array containing each key and its corresponding value. The variable myStr results from joining the values of resArray with blank space and replacing all commas with a blank space.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.