2017-03-19 3 views
0

何らかの理由でオブジェクト内に2つの他のプロパティを結合したい場合、これを行うことはできますか?オブジェクトのプロパティを別の(新しい)プロパティに追加することは可能ですか

たとえば、私が持っている場合:

Cars = { 
    myFirstCar = { model: "mazda", color: "grey" } 
    myCurrentCar = { model: "toyota", color: "black" } 
} 

そして、私はmodel 1、およびcolor 1を結合することをmyFirstCarの内部で別のプロパティを追加したいと言います。このような何か:さておき、あなたのコード内の他の構文エラーから

Cars = { 
    myFirstCar = { model: "mazda", color: "grey", conclusion: model + color } 
    myCurrentCar = { model: "toyota", color: "black" } 
} 
+0

第二の役割は何ですか(あなたの質問に「現在の」)車がありますか?また、この構文はjavascriptではなく、プロパティ名の後に '='をつけることはできません。 – trincot

答えて

2

は、ありません、あなたはまさにそのようにそれを行うことはできません。代わりに、次のようなコードを入力します。

myFirstCar = { model: "mazda", color: "grey" } 
myFirstCar.conclusion = myFirstCar.model + myFirstCar.color; 

残りのコードは無効です。私はどのような構造がわからないのですか?

Cars = { 
    a = b 
    c = d 
} 

となっています。オブジェクトをインスタンス化しようとしている場合は、=の代わりに:を使用してください。配列が必要な場合は、{}の代わりに[]を使用し、変数名と割り当て=を削除します。

+0

どのような構文エラーですか? :o私が気付くことができる唯一のものは、一般的なオブジェクトのコンマです。それ以外に何がありますか? 0_o PS:あなたの返事に感謝します。しかし、私はこのアプローチについて知っています – lluckz

+0

私は私の編集で構文エラーについて詳述しました。 – CollinD

0

あなたはES6 computed property name syntaxでそのような何かを行うことができます。

var cars = { 
 
    myFirstCar: { model: "mazda", color: "grey", 
 
       get conclusion() { return this.model + this.color } }, 
 
    myCurrentCar: { model: "toyota", color: "black" } 
 
} 
 
console.log(cars.myFirstCar); 
 
// Let's update the color, ... and print it again 
 
cars.myFirstCar.color = 'orange'; 
 
console.log(cars.myFirstCar);

スニペットで見ることができるように、これはライブ財産である:それはへの更新を次のプロパティ。

しかし、あなたは複数の車のオブジェクトを持っている場合、この余分なプロパティを定義し、車のオブジェクトのコンストラクタを使用すると便利かもしれません:

function Car(model, color) { 
 
    this.model = model; 
 
    this.color = color; 
 
    Object.defineProperty(this, 'conclusion', { 
 
     get: function() { return this.model + this.color; }, 
 
     enumerable: true 
 
    }); 
 
} 
 

 
var cars = { 
 
    myFirstCar: new Car("mazda", "grey"), 
 
    myCurrentCar: new Car("toyota", "black") 
 
} 
 
console.log(cars.myFirstCar); 
 
console.log(cars.myCurrentCar);

関連する問題