简体   繁体   中英

How to retrieve a value already initialized in an associative array

I wish I didn't have to rewrite some things that could just be copied from a variable in an associative array created.

That is my code, but I got an error that says title is not defined :

const shopLocation = {
  "uccle-heros": {
    title: "Uccle Héros Defré",
    location: [4.334562, 50.043438],
    description: '<strong>'
      + title
      + '</strong>'
      + '<p>'
      + '<a id="test" '
      + 'href="http://www.mtpleasantdc.com/makeitmtpleasant" '
      + 'target="_blank" '
      + 'title="Opens in a new window">'
      + 'Make it Mount Pleasant</a>'
      + 'is a handmade and vintage market and afternoon of live '
      + 'entertainment and kids activities. 12:00-6:00 p.m.'
      + '</p>'
  }
};

You need to use a getter :

 const shopLocation = { "uccle-heros": { title: "Uccle Héros Defré", location: [4.334562, 50.043438], get description() { return '<strong>' + this.title + '</strong><p><a id="test" href="http://www.mtpleasantdc.com/makeitmtpleasant" target="_blank" title="Opens in a new window">Make it Mount Pleasant</a> is a handmade and vintage market and afternoon of live entertainment and kids activities. 12:00-6:00 pm</p>' } } }; console.log(shopLocation)

In addition to @Spectric's answer , use interpolated strings . Much more readable:

const shopLocation = {
  "uccle-heros": {
    title: "Uccle Héros Defré",
    location: [4.334562, 50.043438],
    get description() {
      return `
        <strong>${this.title}</strong>
        <p>
          <a
            id="test"
            href="http://www.mtpleasantdc.com/makeitmtpleasant"
            target="_blank"
            title="Opens in a new window"
          >
            Make it Mount Pleasant
          </a>
          is a handmade and vintage market and afternoon
          of live entertainment and kids activities.
          12:00-6:00 p.m.
        </p>`
    }
  }
};

console.log(shopLocation)

Ok first of this is called an object in javascript

secondly in order to reference something nested in a nested object like this you have to call it as such shopLocation['uccle-heros'].title

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM