0

If for some reason I want to combine two of the other properties inside an object, am I able to do this?

For example, if I have:

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

And say I want to add another property inside of myFirstCar that will combine the model one, and the color one. Something like this:

Cars = {
  myFirstCar = { model: "mazda", color: "grey", conclusion: model + color }
  myCurrentCar = { model: "toyota", color: "black" }
}
lluckz
  • 1
  • What is the role of the second ("current") car in your question? Also, this syntax is not javascript which cannot have `=` after property names. – trincot Mar 19 '17 at 18:01

2 Answers2

2

Aside from the other syntax errors in your code, no you can't do that exactly like that. Instead you'd do something like this:

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

The rest of your code is invalid. I'm not sure what the construct

Cars = {
   a = b
   c = d
 }

is supposed to achieve. If you're trying to instantiate an object, use : instead of =. If you want an array, use [] instead of {} and remove the variables names as well as the assignment =.

CollinD
  • 7,304
  • 2
  • 22
  • 45
  • what syntax errorS? :o The only one I can notice is the comma in the general object... what else? 0_o PS: and thanks for your reply, but I know about this approach – lluckz Mar 19 '17 at 18:02
  • I elaborated on the syntax errors with my edit. – CollinD Mar 19 '17 at 18:02
0

You can do something like that with the 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);

As you can see in the snippet, this is a live property: it follows the updates to the properties.

But if you have multiple car objects, it might be useful to use a constructor for car objects, which defines this extra property:

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);
trincot
  • 317,000
  • 35
  • 244
  • 286