4

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

Aero Wang
  • 8,382
  • 14
  • 63
  • 99
  • `forEach` should be invoked on arrays not with an object. If you try on array of objects , it will work – Sridhar May 31 '17 at 04:50
  • `for(var key in object) console.log(key, object);` – sudo May 31 '17 at 04: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 – Jaromanda X May 31 '17 at 04:55
  • ugh - that duplicate needs modernization!!! – Jaromanda X May 31 '17 at 04:55
  • 1
    This is not a very good duplicate, because (1) no answers mention `Object.entries` and (2) it is mainly about chunking. –  May 31 '17 at 05:14
  • I have no idea what you mean by "flat array in the object and do not output map". `object[key]`, where key is the index of a `for...in` loop, or a `forEach` on `Object.keys`, will return the array as-is. –  May 31 '17 at 05:15
  • @torazaburo later i realized it was just the console itself has flatten the array – Aero Wang May 31 '17 at 05:17

3 Answers3

8

Try this,

Object.keys(object).forEach(key=>{
    console.log(key ,object[key]);
})
Anurag Awasthi
  • 6,115
  • 2
  • 18
  • 32
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]);
sudo
  • 323
  • 3
  • 12
-1

Use this,

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