2

In javascript, is there anyway to set a value equal to a previous key that was declared during initialization? for example,

const object = {
  a: "test",
  b: a
    }
 
 console.log(object)

or

const object = {
  a: "test",
  b: object.a
    }
 
 console.log(object)

How can I achieve this result in the console?

    { a: 'test', b: 'test' }

I understand that this is redundant, so let me explain what I'm trying to achieve.

I want to be able to set a url in one value, and then add to it using a previous value. The reason for this is to clean up the code and set formulas into one object.

Example

const object = {
  base_url: "www.google.com",
  images_url: `${base_url}/images`,
  maps_url: `${base_url}/maps`
    }
 
 console.log(object)
  • 2
    Isn’t this a bit redundant? Curious, can you elaborate on your use case for which you would need this kind of functionality? – esqew Oct 01 '21 at 17:24
  • 1
    you can't do it at the same time as object initialization. – Daniel A. White Oct 01 '21 at 17:26
  • 1
    This is not doable. You can't refer an object during its initialisation. – DraganS Oct 01 '21 at 17:26
  • 1
    Maybe this answers your question https://stackoverflow.com/questions/2787245/how-can-a-javascript-object-refer-to-values-in-itself/2787259 – SniperHerz Oct 01 '21 at 17:27
  • 1
    You can't do it during initialization, but you can afterwards. `var object = { a: "test" }; object.b = object.a;` – skyline3000 Oct 01 '21 at 17:28
  • 1
    You can have a getter that refers to another field. Looks like a field to the client code. – Wiktor Zychla Oct 01 '21 at 17:33
  • 1
    Declare the google Variable outside the object and then inside properties just use it. This is a safe way where you know your variable is not changing (which is why i guess you are trying to refer to the same value). There is no better way to do it the way you want – Tushar Shahi Oct 01 '21 at 17:33
  • 1
    If you're willing to change it from an object to a class you could achieve something like this in the constructor; might make sense depending on your use case. – Alexander Nied Oct 01 '21 at 17:39

2 Answers2

4

The closest thing I can think of in Javascript is to use a getter.

const object = {
  a: "test",
  get b(){
   return this.a+"something else";
  }
    }
 
console.log(object)
zelite
  • 1,478
  • 16
  • 37
3

Getter/Setters will save your day

const object = {
  a: "test",
  get b(){return this.a}
 }
 
 console.log(object)
Siddharth
  • 543
  • 6
  • 15