DEV Community

Weerasak Chongnguluam
Weerasak Chongnguluam

Posted on

Merge object or array ของ JavaScript ด้วย spread (...) operator

เนื่องจากว่าไม่ได้ใช้ JavaScript เป็นงานหลัก นานๆได้มาอ่านทีก็ได้รู้เรื่องใหม่ๆที่ไม่ค่อยได้รู้มาก่อนบ้าง อย่างเช่น เมื่อวานเจอโค้ดนึงเขียนแบบนี้

options = {...options, ...plugins}
Enter fullscreen mode Exit fullscreen mode

ดูงงๆว่ามันทำอะไรใน statement นี้ พอไปค้นดูก็เจอว่า ... เนี่ยมันคือ spread operator เอาไว้กระจายของใน Object (key:value) หรือใน Array ออกมาเป็น element นึงใน object ใหม่ หรือใน array ใหม่

ทีนี้แบบข้างบนมันเลยคือเอา options มารวมกับ plugins แล้ว assign กลับไปที่ options อีกที ก็คือการ merge สอง object เข้าด้วยกันนั่นเองโดยถ้า plugins มี key ซ้ำกับ options มันก็จะเอาของใน plugins มาทับไปแทน

ก็อย่างที่บอกว่ามันใช้กับ Array ได้ด้วย ตัวอย่างเช่น

array1 = [10, 20, 30]
array2 = [40, 50, 60]
result = [...array1, ...array2]
Enter fullscreen mode Exit fullscreen mode

นี่ก็เป็นตัวอย่างหนึ่งของการเอา spread syntax มาช่วย merge Object หรือ Array ถ้าอยากดูรายละเอียดมากกว่านี้ลองดูได้ที่ document ของทาง MDN Web Docs ที่นี่ครับ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

ขอฝาก Buy Me a Coffee

สำหรับท่านใดที่อ่านแล้วชอบโพสต์ต่างๆของผมที่นี่ ต้องการสนับสนุนค่ากาแฟเล็กๆน้อยๆ สามารถสนับสนุนผมได้ผ่านทาง Buy Me a Coffee คลิ๊กที่รูปด้านล่างนี้ได้เลยครับ

Buy Me A Coffee

ส่วนท่านใดไม่สะดวกใช้บัตรเครดิต หรือ Paypal สามารถสนับสนุนผมได้ผ่านทาง PromptPay โดยดู QR Code ได้จากโพสต์ที่พินเอาไว้ได้ที่ Page DevDose ครับ https://web.facebook.com/devdoseth

ขอบคุณครับ 🙏

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay