0

Is there a way to use a fat arrow with an object?

The following code prints out the contents of the array "test" in the console.

//With array
let test = [1, 2, 3, 4];
test.forEach(number => console.log(number));

I'm looking for a way to have the same output but with "test" being an object, not an array (like below). is there a (relatively) simple way of doing this?

//With object
let test = {
  a: 1,
  b: 2,
  c: 3,
  d: 4
}
test.forEach(number => console.log(number));
  • ES6 arrows are used to make arrow functions : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions Therefore, you can use them as you would with a usual function – Seblor Jun 21 '18 at 08:37
  • 3
    Possible duplicate of [Iterate through object properties](https://stackoverflow.com/questions/8312459/iterate-through-object-properties) – Liam Jun 21 '18 at 08:38
  • 1
    An arrow function is just a short hand, your issue here isn't the arrow function it's your loop. – Liam Jun 21 '18 at 08:38

5 Answers5

7

There is a couple of ways to do this:

Object.keys(test).forEach(key => console.log(test[key]));

Object.keys is the oldest method, available since ES5.

However, as you're using ES6 method you can probably use newer methods:

Object.keys(test) // ['a', 'b', 'c', 'd']
Object.values(test) // [1, 2, 3, 4]
Object.entries(test) // [['a', 1], ['b', 2], ['c', 3], ['d', 4]]
Axnyff
  • 8,235
  • 3
  • 31
  • 36
2

Array methods cannot be used on an object. Use Object.keys to get an array of object's keys, then use array method forEach

let test = {
  a: 1,
  b: 2,
  c: 3,
  d: 4
}
Object.keys(test).forEach(number => console.log(test[number]));
brk
  • 46,805
  • 5
  • 49
  • 71
1

for array you can use array.forEach() and for object you need to use Object.values(object).forEach() for values and Object.keys(object).forEach() for object keys. :D

//With array
var test = [1, 2, 3, 4];
console.log("Array");
test.forEach(number => console.log(number));

console.log("Obejct");
//With object
var testObj = {
  a: 1,
  b: 2,
  c: 3,
  d: 4
}
Object.values(testObj).forEach(number => console.log(number));
Liam
  • 25,247
  • 27
  • 110
  • 174
Akhil Aravind
  • 5,388
  • 15
  • 34
0

You have following options

1) Object.keys()

test = {
  a: 1,
  b: 2,
  c: 3,
  d: 4
}

Object.keys(test).forEach(key => console.log(test[key]))

Object.keys returns an array of keys of the object it was called on.

2) Object.values()

test = {
   a: 1,
   b: 2,
   c: 3,
   d: 4
}

Object.values(test).forEach(value=> console.log(value))

Object.values Returns an array whose elements are the enumerable property values found on the object.

It worked yesterday.
  • 4,275
  • 10
  • 43
  • 78
0

Or you can use Object.values()

let test = {
  a: 1,
  b: 2,
  c: 3,
  d: 4
}
Object.values(test).forEach(number => console.log(number));
samet
  • 518
  • 5
  • 8