0

This is the code

const restaurant = {
    name: 'Ichiran Ramen',
    address: `${Math.floor(Math.random() * 100) + 1} Johnson Ave`,
    city: 'Brooklyn',
    state: 'NY',
    zipcode: '11206',

I want to create a variable "fullAddress" which should point to a string using the information from restaurant fullAdress should have address city state and zipcode.

my approach is

let fullAddress = restaurant.address;
fullAddress += restaurant.city;
fullAddress += restaurant.state;
fullAddress += restaurant.zipcode;

but this seems odd to me and lengthy and it is not having spaces in between.

any help will be highly appreciated.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Ali Ahmed
  • 155
  • 9
  • 1
    Hint: use [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) – Heretic Monkey Mar 16 '21 at 13:32
  • Does this answer your question? [Concatenate multiple object property values into one](https://stackoverflow.com/questions/38754054/concatenate-multiple-object-property-values-into-one) – Heretic Monkey Mar 16 '21 at 13:33

2 Answers2

3

You can define a getter property

const restaurant = {
    name: 'Ichiran Ramen',
    address: `${Math.floor(Math.random() * 100) + 1} Johnson Ave`,
    city: 'Brooklyn',
    state: 'NY',
    zipcode: '11206',
    get fullAddress() {
      const { address, city, state, zipcode } = this;
      return `${address} ${city} ${state} ${zipcode}`;
    }
}

console.log(restaurant.fullAddress);
Vanojx1
  • 5,574
  • 2
  • 23
  • 37
  • Please add your answer to the identified duplicate question rather than answering this one. – Heretic Monkey Mar 16 '21 at 13:38
  • I think the 2 questions are sligtly different. The answer you identified regards objects modification, this one is about getting values. – Vanojx1 Mar 16 '21 at 14:38
1

Your approach is not overly verbose and it is defensibly clear to read, however you aren't concatenating a comma and space in between the address components. To get the correct result using your approach:

let fullAddress = restaurant.address;
fullAddress += ', ';
fullAddress += restaurant.city;
fullAddress += ', ';
fullAddress += restaurant.state;
fullAddress += ', ';
fullAddress += restaurant.zipcode;

However, if you would like a more succinct approach, and assuming you are working in a modern (ES6) environment, you can use template literals for this.

For example, if you wanted the final string to be 123 Johnson Ave, Brooklyn, NY, 11206

You would write this as:

const fullAddress = `${restaurant.address}, ${restaurant.city}, ${restaurant.state}, ${restaurant.zipcode}`;

Note that the syntax for template literals uses backticks, not normal quotes.

More information about template literals on MDN.

Tim Reid
  • 36
  • 7