2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめての記事投稿
Qiita Engineer Festa20242024年7月17日まで開催中!

(Javascript)スプレッド構文(...)を使ってオブジェクトを展開してみよう

Posted at

初投稿の記事になります。

1つのオブジェクトを展開し、変数に代入してみる

a.js
const userObject = { userName: 'John', age: 20, city: 'New York' }
const userObjectCopy = { ...userObject }
console.log(userObjectCopy)
{ userName: 'John', age: 20, city: 'New York' }

2つのオブジェクトを展開し、変数に代入してみる

b.js
const personObject = { userName: 'John', age: 20 }
const dataObject = { city: 'New York', job: 'Engineer' }
const mergedUserObject = { ...personObject, ...dataObject }
console.log(mergedUserObject)
{ userName:"John", age:20, city:"New York", job:"Engineer"}

(発展)2つのオブジェクトに同じプロパティがある場合

c.js
const personObject = { userName: 'John', city: 'New York' }
const dataObject = { city: 'Tokyo', job: 'Engineer' }
const mergedUserObject = { ...personObject, ...dataObject }
console.log(mergedUserObject)

両オブジェクトとも、cityプロパティを持っているが果たして結果は…

{ userName:"John", city:"Tokyo", job:"Engineer"}

dataObjectオブジェクトの値("Tokyo")が採用されていることが確認できた。
2つのオブジェクト間でプロパティが競合した場合、2つ目のオブジェクトの値が採用される。(後勝ちとなる。)

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?