Indraraj26
Indraraj26

Reputation: 1976

template literals inside the javascript object [es6]

how can i assign object value to other key of object. I tried this but it is not working all i get is undefined.

let test = {
 id:1,
 name:this.test.id
}

let test2 = {
 id:1,
 name:`hello, ${this.id}`
}

console.log(test)
console.log(test2);

Upvotes: 0

Views: 99

Answers (1)

Ori Drori
Ori Drori

Reputation: 192652

When you create the object this is the context in which the object is created, and not object itself (since it doesn't exist yet). Use a getter to compute the value.

let test = {
 id:1,
 get name() { return this.id }
}

let test2 = {
 id:1,
 get name() { return `hello, ${this.id}` }
}

console.log(test)
console.log(test2);

Upvotes: 5

Related Questions