🍺

何かと便利なObject.assign()

2022/10/16に公開1

外部APIを叩いて、返ってきたデータがresponseであるとする。

const response = {
  data: [
    {
      name: "Wiskey",
      price: "350",
      percentage: "10",
    },
    {
      name: "Lemon Sour",
      price: "350",
      percentage: "5",
    },
    {
      name: "Beer",
      price: "350",
      percentage: "5",
    },
    {
      name: "Plum shu",
      price: "350",
      percentage: "12",
    },
    {
      name: "Vodka",
      price: "350",
      percentage: "24",
    },
  ],
};

このままだと使いづらい。

ということで、dataの中身だけ取り出して別の変数名にしたい時は下記のようにする。


const { data: alcohols = [] } = response;

console.log(alcohols)
[
  { id: 1, name: 'Wiskey', price: '350', percentage: '10' },
  { id: 2, name: 'Lemon Sour', price: '350', percentage: '5' },
  { id: 3, name: 'Beer', price: '350', percentage: '5' },
  { id: 4, name: 'Plum shu', price: '350', percentage: '12' },
  { id: 5, name: 'Vodka', price: '350', percentage: '24' }
]

alcoholsのインスタンスを作りたいときは、Object.assignが使える。
第一引数にpush先を置き、第二引数にコピーしたいオブジェクトを置く。

コピー後とコピー前で比較してみると、同じではないことがわかる。


const copy_alcohol = Object.assign({}, alcohols);
console.log(copy_alcohol === alcohols); // false

さらにObject.assignを活用すれば、オブジェクトに対して上書きを加えることもできる。

const assign_attributes = {
  data: [
    {
      name: "highball",
      price: "200",
      percentage: "5",
    },
    {
      name: "sake",
      price: "1000",
      percentage: "23",
    },
  ],
};

const { data: update = []} = assign_attributes;

const assigned_alcohols = Object.assign(copy_alcohol, update);
// {
//     '0': { name: 'highball', price: '200', percentage: '5' },
//     '1': { name: 'sake', price: '1000', percentage: '23' },
//     '2': { name: 'Beer', price: '350', percentage: '5' },
//     '3': { name: 'Plum shu', price: '350', percentage: '12' },
//     '4': { name: 'Vodka', price: '350', percentage: '24' }
//   }

何かと便利、Object.assign()

参考文献

https://stackoverflow.com/questions/32925460/object-spread-vs-object-assign

Discussion

yuzupozuyuzupozu

普通にconst alcohol = response.dataとやればいいのでは。