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
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.