Set value within an object equal to the previous value

Asked

Viewed 44 times

0

Is there any way to define the value of an object to be equal to the previous object?

Example:

var obj = {a: 1, b: obj.a};

I tried used b: this.a also but created an html Circle tag, I did not understand why.

Actually, I’m managing to do it this way:

var obj = {a: 1, b: null};
obj.b = obj.a;

Is there any other way more effective?

  • 1

    Before submitting an answer I ask, would the use of a property solve your problem? Example: var obj = {a: 1, get b(){return this.a}};

  • No, what I want is for two or more elements inside the object to have the same values. EX: var obj = {a: 1, b: /*valor ou ponteiro de a*/, c: 2, d: /*valor ou ponteiro de c*/, e: etc...}

  • 1

    Before you say it is not what you seek to do var obj = {a: 1, get b(){return this.a}}; console.log(obj); obj.a=33; console.log(obj); console.log(obj.b);

  • I used the console.log(obj) and obj. b didn’t show up, but now I’ve seen that it does exist. Sorry, that’s what I was really looking for.

1 answer

0

You could use the spread operator (...):

An example:

const obj = {a: 1, b: 2};
const obj1 = {c:3, ...obj};

or try if you are using an older javascript version Object.assign():

const obj = {a: 1, b: 1};
const obj2 = Object.assign({c:3, d: obj})

For a more complete use and check more examples recommend viewing the mdn documentation.

  • what I want is to set the value obj. b to be equal to obj. a if possible in only one line of code

Browser other questions tagged

You are not signed in. Login or sign up in order to post.