1. ホーム
  2. javascript

[解決済み] ES6で2つのオブジェクトをマージする [重複].

2022-09-27 18:12:43

質問

この質問は以前にもされたことがあると思いますが、私が探している答えがなかなか見つからないので、ここに書いておきます。

私は以下のように2つのオブジェクトを持っています。

const response = {
  lat: -51.3303,
  lng: 0.39440
}

let item = {
  id: 'qwenhee-9763ae-lenfya',
  address: '14-22 Elder St, London, E1 6BT, UK'
}

これらを結合してこのような形にする必要があります。

item = {
  id: 'qwenhee-9763ae-lenfya',
  address: '14-22 Elder St, London, E1 6BT, UK',
  location: {
    lat: -51.3303,
    lng: 0.39440
  }
}

こうすればいいんだろうけど

item.location = {}
item.location.lat = response.lat
item.location.lng = response.lng

しかし、ES6ではクールなデストラクチャリング/アサイメントが導入されたので、これはもうベストな方法ではないと感じています。深いオブジェクトマージを試みましたが、残念ながらサポートされていません :( また、いくつかのramda関数に目を通しましたが、適用できるものは見つかりませんでした。

では、ES6を使用してこれら2つのオブジェクトをマージする最良の方法は何でしょうか?

どのように解決するのですか?

この場合 Object.assign() を使って、新しいオブジェクトにマージすることができます。

const response = {
  lat: -51.3303,
  lng: 0.39440
}

const item = {
  id: 'qwenhee-9763ae-lenfya',
  address: '14-22 Elder St, London, E1 6BT, UK'
}

const newItem = Object.assign({}, item, { location: response });

console.log(newItem );

また オブジェクトの広がり これは ECMAScript の Stage 4 の提案です。

const response = {
  lat: -51.3303,
  lng: 0.39440
}

const item = {
  id: 'qwenhee-9763ae-lenfya',
  address: '14-22 Elder St, London, E1 6BT, UK'
}

const newItem = { ...item, location: response }; // or { ...response } if you want to clone response as well

console.log(newItem );