7

I have a data structure similar to:

var object = {
  name: "a",
  number: "1",
  mission: ['a','b','c']
}

Now I want to update them into the database so I need to walk them.

I tried:

object.forEach(function(value, key, map){
  console.log('value: ' + value + ', key: ' + key + ', map:' + map);
});

And then the console report an error: object.forEach is not a function

7
  • forEach should be invoked on arrays not with an object. If you try on array of objects , it will work Commented May 31, 2017 at 4:50
  • for(var key in object) console.log(key, object); Commented May 31, 2017 at 4:51
  • 2
    In modern JS Object.entries(object).forEach(([key, value]) => console.log(`key: ${key}, value: ${value}`)); With polyfills and transpilers this should run anywhere :p Commented May 31, 2017 at 4:55
  • ugh - that duplicate needs modernization!!! Commented May 31, 2017 at 4:55
  • 1
    This is not a very good duplicate, because (1) no answers mention Object.entries and (2) it is mainly about chunking. Commented May 31, 2017 at 5:14

3 Answers 3

14

Try this,

Object.keys(object).forEach(key=>{
    console.log(key ,object[key]);
})
Sign up to request clarification or add additional context in comments.

3 Comments

thanks, how do i output map? also this seems to flat array into string...
@AeroWang well inforEach third argument is actual array itself on which you have called forEach. Array is converting into string because we are adding it with a string.
how to keep it as an array?
0

You could do it like this.

var object = {
  name: "a",
  number: "1",
  mission: ['a','b','c']
}
for(var key in object) console.log(key, object[key]);

2 Comments

thanks, how do i output map? also this seems to flat array into string...
Why var rather than let or const?
-1

Use this,

 for (var item in object) {
    console.log('value: ' + object['name'] + ', key: ' + object['number'] + ', map:' + object['mission']);
 }

2 Comments

no, the key in the object will change, they might not be name, number, and mission
Why are you looping over the keys with item, but then not doing anything with it?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.