1

How to use the spread operator to access element in my array of object ?

const array = [{ obj: 1},{ obj: 2}]

console.log([...array].obj)
// Output undefined 

console.log([...array.obj])
// Output Uncaught TypeError

I've seen this post Use spread operator on objects array? which is quite similar but they do not try to access elements.

So is it possible to use spread operator on array of object to access elements ? If so how ?

user15873596
  • 155
  • 1
  • 9
  • 2
    What are you expecting as output? Both `1` and `2`? – Ivar May 19 '21 at 07:42
  • Yes that's right – user15873596 May 19 '21 at 07:43
  • `[...array]` -> clones `array` into a new array. You take the `.obj` property of that array. Arrays don't have an `.obj` property, so you get undefined. `[...array.obj]` -> spread `array.obj` as an array. Since arrays don't have an `.obj` property, you're doing an array spread of `undefined`. That causes an error. – VLAZ May 19 '21 at 07:46
  • 2
    Long story shorts, you can't use the spread operator like that in JS. – Ivar May 19 '21 at 07:47

2 Answers2

5

You're probably looking for map

What you need is array.map(element => element.obj)

Here's what's wrong with your attempts:

  • console.log([...array].obj): You're spreading the array into a new array, and then you're logging the obj property of the new array, which is undefined, as expected

  • console.log([...array.obj]): You're trying to spread the obj property of array, which is also undefined, meaning you're trying to spread undefined, which throws you an error

Ron B.
  • 1,502
  • 2
  • 7
  • Nop sorry, my question is really what is it. I know how to browse an object using function like map, forEach, for... But that's not my question. Thanks though – user15873596 May 19 '21 at 07:45
  • Thanks again for you edit and help. So no way to use the spread syntax to access my elements ? I must use a function ? – user15873596 May 19 '21 at 07:46
  • 1
    @user15873596 spreading doesn't work like mapping at all. So...no, you cannot make it work like mapping. – VLAZ May 19 '21 at 07:46
  • Thanks @VLAZ, that was what I was looking for :) – user15873596 May 19 '21 at 07:47
  • 1
    @user15873596 A spread operator is just like what it says, it's used to spread an array into a new array, or an object key-value pairs into a new object, as is. You can't modify stuff using this operator – Ron B. May 19 '21 at 07:48
3

Short answer, no.

We cannot use spread operator on array of object to access elements.

As @VLAZ said in a comment

Spreading doesn't work like mapping at all. So...no, you cannot make it work like mapping

user15873596
  • 155
  • 1
  • 9