1
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?

More than 5 years have passed since last update.

JavaScript オブジェクトの分割代入 オブジェクトの異なる名前のプロパティへ代入する

Posted at

オブジェクトの分割代入で名前を変えて変数に代入できるが、
オブジェクトのプロパティに名前を変えて代入できるのだろうか。

変数に代入はもちろんできる。

var o = {p: 42, q: true, r: 'hoge'};

var {p: foo, q: bar, r: baz} = o; 
console.log(foo); // 42 
console.log(bar); // true  
console.log(baz); // 'hoge'  

オブジェクトの名前の違うプロパティに代入はどうだ。


var o = {p: 42, q: true, r: 'hoge'};

var o2 = {};
({p: o2.pp, q: o2.qq, r: o2.rr} = o);
console.log(o2); // {pp: 42, qq: true, rr: "hoge"}

できた!
けど、1つずつ代入する方が読みすい、かな。

var o2 = {};
o2.pp = o.p;
o2.qq = o.q;
o2.rr = o.r;

参考
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

1
0
2

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
1
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?