javascriptobject-destructuring

Difference between [...obj] and {...obj}


I know about the spread operator ... in JavaScript. We can use it on both arrays and objects:

let user = {
  name: "aman",
  rollno: 11
}

let newobj1 = {...user}
let newobj2 = [...user]
console.log(newobj1)
console.log(newobj2)

Why does newobj2 give an error, TypeError: user is not iterable, but newobj1 works fine?


Solution

  • {...user} just creates a new object with the same properties as user.

    [...user], on the other hand, iterates through the object and adds the values it finds into the array it returns. If there is no way to iterate, as there isn't by default on a plain object (as opposed to an array), then this doesn't work and raises the error you've quoted.

    As always, there is much more information about this on MDN. Note in particular the following section:

    Spread syntax (other than in the case of spread properties) can only be applied to iterable objects like Array, or with iterating functions such as map(), reduce(), and assign().

    Many objects are not iterable, including Object:

    let obj = {'key1': 'value1'};
    let array = [...obj]; // TypeError: obj is not iterable
    

    To use spread syntax with these objects, you will need to provide an iterator function.

    And note that the "spread syntax" being referred to here is the "array spread" version. "Object spread" is rather different and explained on this part of the page,