Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

213
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

{...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,

about 4 years ago · Juan Pablo Isaza Relatório

0

{...user}

means that you create new object and spread all the data from user inside it.

When you suppose to execute

[...user]

you tries to create brand new array and then spread the user object inside.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda