2016-11-03 6 views
13

をグループ化:ES6 /:オブジェクトが他の部分と構造化代入 - 私が持っている

const props = { 
    gallery: [], 
    select:() => null, 
    one: 1, 
    two: 2, 
} 

私はそれをdestructureことができます。

  • const {gallery, select, ...other} = props 
    

    私は今、三つの変数を持っていますギャラリー = []

  • = {one: 1,two: 2} = () => null

を選択すると、グループ化指定にdestuctureすることが可能ですか?このような

何か(これは仕事に行くのではありませんが、私は私が何をしようとしていますかを確認するには、clearであると思います):

  • const {{gallery, select}: specific, ...other} = props 
    

    は、だから私は2変数を持つことになります特定 = {gallery: [], select:() => null}

  • = {one: 1,two: 2}

私はより高いレベルでそれを解決し、このように小道具を構築することができます:

const props = { 
    specific: { 
    gallery: [], 
    select:() => null, 
    }, 
    other: { 
    one: 1, 
    two: 2, 
    } 
} 

しかし、これは非構造で可能である場合、私はちょうど疑問に思って。

+0

はおそらく[拡がり性](https://github.com/sebmarkbage/ecmascript-rest-spread#spread-properties)で行うことができているが、それは利用できませんまだES6で –

+0

@SamKuhmonenそれはES6で決して利用できません。 ES6の仕様は既に確定しています。 –

+0

@ゴスドあいまいな言葉遣いは、私はそれがまだESバージョン6で利用可能ではないが、後のものであるかもしれないことを意味した。 –

答えて

8

これはどうですか? othersにはspecificのデータも含まれており、最初にpropsにアクセスする必要があります(これは改善される可能性があります)。しかし、基本的には構造化しながらグループ化していると思います。属性が存在しない場合、デフォルト値を割り当てることができるので、それは動作します:

const props = { 
 
    gallery: [], 
 
    select:() => null, 
 
    one: 1, 
 
    two: 2, 
 
} 
 

 
const {gallery : gal, select : sel} = props; 
 
const {specific: specific={gallery: gal, select: sel}, ...others} = props; 
 

 
console.log(specific); 
 
console.log(others);

EDIT

あなたはまたして

const {gallery : gal, select : sel} = props; 
const {specific: specific={gallery: gal, select: sel}, ...others} = props; 

を変更することができます。

const {specific: specific={gallery: props.gallery, select: props.select}, ...others} = props; 

1行に入力してください。

また、maioman's answerは私がspecificデータを含むothersと述べたと、直接小道具にアクセスしていない問題を解決します。あなたがこれを行うことが限界に

5

ストレッチ構文(と読みやすさ):

我々が得る最後に

const props = { 
 
    gallery: [], 
 
    select:() => null, 
 
    one: 1, 
 
    two: 2, 
 
} 
 

 
/** destructuring assignment **/ 
 
const { 
 
    gallery, //extract the gallery prop 
 
    select, //extract the select prop 
 
    specific: specific={gallery, select}, 
 
    // create `specific` setting gallery and select props through default value assignment 
 
    ...others // assign to others the rest of non extracted props properties 
 
} = props; 
 

 
console.log(specific); 
 
console.log(others);

(コードの説明がコメントです) galleryselectというオブジェクトがありましたが、新しいspecificオブジェクトのプロパティにすることに成功しました。

使い方警告:オブジェクトの広がりはまだ提案

+0

私はかなりstackoverflowに新しいので、私は本当に確実ではないと私は私の前提に間違っているかもしれないが、私の答えを使用して変更されたようだ...私のコメントではなく、それは新しい答えです。 –

+0

@CésarLandesaスニペットが同じボイラープレートを共有していても、解決策は異なるので、IMHOは大丈夫です... – maioman

+0

しかし、解決策は主な問題を解決するために同じ考え方に基づいています。あなたはそのコンセプトを改善しましたが、私のコードと主なアイデアに基づいています。私はそれが遠近法の問題だと思うが、それは私のアイデアの修正のように見えるものであり、十分な解決策ではない。 –

関連する問題