-2

Is there a way to simplify this expression?

const car = { owner: 'john' }
const assets = { house: { owner: 'paul'}, car: car}

As the key in assets takes the variable name car, is it a way to avoid redefining the key name?

Something like this:

const assets = { house: { owner: 'paul'}, car}

Thank you!

FZs
  • 11,931
  • 11
  • 28
  • 41
Jake He
  • 1,389
  • 2
  • 18
  • 31
  • 6
    Perhaps I'm misunderstanding the question, but your "something like this" example is valid. You can do it literally, exactly like that. – ray hatfield May 25 '19 at 07:23
  • 1
    [Shorthand property names](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#New_notations_in_ECMAScript_2015) – adiga May 25 '19 at 08:05

2 Answers2

0

All of your two solutions will work.

const assets = { house: { owner: 'paul'}, car: car}

... does exactly the same as ...

const assets = { house: { owner: 'paul'}, car}

None of these solutions will redefine the variable car.

The second solution is called shorthand property definiton and works only in ES2015 or newer.

FZs
  • 11,931
  • 11
  • 28
  • 41
0

Yes, it works, and it's known as shorthand property notation (ES6):

const car = {
  owner: 'john'
}
const assets = {
  house: {
    owner: 'paul'
  },
  car
};

console.log(assets);
.as-console-wrapper { max-height: 100% !important; top: auto; }

Note that this is different from spreading - shorthand properties will make a new object, spreading (...) just directly attach the properties:

const car = {
  owner: 'john'
}
const assets = {
  house: {
    owner: 'paul'
  },
  ...car
};

console.log(assets);
.as-console-wrapper { max-height: 100% !important; top: auto; }
Jack Bashford
  • 38,499
  • 10
  • 36
  • 67