DEV Community

Willian Justen
Willian Justen

Posted on • Originally published at willianjusten.com.br on

2

Juntando arrays e objetos com Spread syntax no JavaScript

Introdução

Fala pessoal, eu recentemente comecei uma série de vídeos com dicas bem rápidas lá no meu canal do YouTube, mas como eu também gosto de texto e também quero facilitar a busca seja pelo Google ou pelo YouTube, vou portar os vídeos para cá também. Espero que dê certo =)

Vídeo

Utilizando o poder do ...Spread

Antigamente para fazer esse tipo de formatação nós precisávamos fazer algum método próprio ou cair em soluções como o Lodash. Mas agora graças ao Spread Operator nós conseguimos fazer isso de forma simples, somente utilizando o JS puro.

Vamos ver abaixo alguns exemplos na prática:

const arrayOne = [1, 2, 3, 4]
const arrayTwo = [5, 6, 7, 8]

// juntando os arrays
const newArray = [...arrayOne, ...arrayTwo] // [1, 2, 3, 4, 5, 6, 7, 8]

// funciona com objetos também!
const props = { id: '1', name: 'Willian' }
const moreProps = { age: 30, height: 178 }

const newObj = { ...props, ...moreProps } // { id: '1', name: 'Willian', age: 30, height: 178 }

// E você também consegue sobrepôr valores
const defaultProps = { id: '1', name: 'Willian' }
const newProps = { id: '3', age: 30 }

// Chaves iguais são sobreescritas pelo último objeto passado
const propsObj = { ...defaultProps, ...newProps } // { id: '3', name: 'Willian', age: 30 }
Enter fullscreen mode Exit fullscreen mode

Conclusão

E aí, gostou da dica? Se curtiu, não deixa de se inscrever lá no canal do YouTube para essa e mais outras dicas.

Retry later

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay