9
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

スプレッド構文について学習してみた

Posted at

スプレッド構文の基本

JavaScript

const obj = {
    id: '0001',
    name: 'Taro',
    age: '25',
    from: 'Japan',
};

const copyObj = { ...obj };

console.log(obj);
console.log(copyObj);

結果

image.png

コピー元を更新してみる

JavaScript

const obj = {
    id: '0001',
    name: 'Taro',
    age: '25',
    from: 'Japan',
};

const copyObj = { ...obj };
obj.id = '0002';

console.log(obj);
console.log(copyObj);

結果

image.png
コピー元のみ更新される ※上部

コピー元を更新してみる(入れ子の場合)

JavaScript

const obj = {
    1: {
        id: '0001',
        name: 'Taro',
        age: '25',
        from: 'Japan',
    },
    2: {
        id: '0002',
        name: 'Ayaka',
        age: '23',
        from: 'USA',
    },
    3: {
        id: '0003',
        name: 'Yuki',
        age: '20',
        from: 'Japan',
    },

};

const copyObj = { ...obj };
obj[3].name = 'Risa';

console.log(obj);
console.log(copyObj);

結果

image.png

入れ子の場合は、子供のオブジェクトのは一緒に変更されてしまう、、、
上記を避けたいとき

JavaScript

const obj = {
    1: {
        id: '0001',
        name: 'Taro',
        age: '25',
        from: 'Japan',
    },
    2: {
        id: '0002',
        name: 'Ayaka',
        age: '23',
        from: 'USA',
    },
    3: {
        id: '0003',
        name: 'Yuki',
        age: '20',
        from: 'Japan',
    },

};

const copyObj = JSON.parse(JSON.stringify(obj));
obj[3].name = 'Risa';

console.log(obj);
console.log(copyObj);


image.png

JSON.stringify() でオブジェクトを文字列に変換し、 JSON.parse() で文字列をオブジェクトに変換することでcopyObj は obj とは別のオブジェクトを参照しているのでobj の変更がcopyObj には反映されない。

9
0
1

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
9
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?