Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I reference an attribute inside the same object

I’m trying to cut down on a lot of the manual typing id need to do when creating objects for a small program

currently the object structure looks like this:

test = [
  {
    entry: "001",
    name: "Name"
    image: `link/001`,
    types: ["type1"],
  },
]

what i’m trying to do is allow for automatic linking of the entry to the image using the this keyword but it’s consistently coming back as undefined

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

test = [
  {
    entry: "001",
    name: "Name"
    image: `link/${this.entry}`,
    types: ["type1"],
  },
]

I tried creating a function inside of the object to create the result id want then return it but also undefined

test = [
  {
    entry: "001",
    name: "Name"
    image: getNumber(this) {
         return `link/${this.entry}`
},
    types: ["type1"],
  },
]

As well as this I also checked out various similar issues on stack overflow and they didn’t seem to address my problem as expected

>Solution :

You have the right idea but the wrong syntax:

const test = [
  {
    entry: "001",
    name: "Name",
    get image() {
      return `link/${this.entry}`;
    },
    types: ["type1"],
  },
  {
    entry: "002",
    name: "Name",
    get image() {
      return `link/${this.entry}`;
    },
    types: ["type1"],
  },
  // ... you can add more entries here
];

console.log(test)

In most cases it is actually easier to do this with a method such as map.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading