bsky
bsky

Reputation: 20222

Assign an object property value to another property while declaring the object

I have the following Javascript code:

var container = {
  first: {
    a: 1,
    b: 'someString'
  },

  second: Object.assign({
      c: 34,
      d: 'something else'
    },
    this.first
  )
}

console.log(container)

This prints:

{ first: { a: 1, b: 'someString' },
  second: { c: 34, d: 'something else' } }

However, I would like it to be:

{ first: { a: 1, b: 'someString' },
  second: { c: 34, d: 'something else', a: 1, b: 'someString'} }

So I would like all the (key, value) pairs from first to also be present in second. How can that be done?

Upvotes: 1

Views: 298

Answers (4)

cнŝdk
cнŝdk

Reputation: 32145

Problem:

In fact you are assigning the content of second with undefined, because at the time you are trying to refer the first property, at the assignement time, it doesn't exist yet in your container object.

Solution:

You need either to store the content of first property in an object before the assignement or create your container object with only first property and then define container.second property to get first value combined with second value.

This is how can be your code:

var container = {
  first: {
    a: 1,
    b: 'someString'
  }
};

container.second = Object.assign({
    c: 34,
    d: 'something else'
  },
  container.first
);

console.log(container)

Upvotes: 1

var container = {
    first: {
        a: 1,
        b: 'someString'
    }
}

container.second = Object.assign(
    {
        c: 34,
        d: 'Something else'
    },
    container.first
)

Upvotes: 0

Vignesh Raja
Vignesh Raja

Reputation: 8731

You may looking for this.

var a = new function(){
    this.b = {name:"Vignesh",place:"India"};
    this.c = {name:"Vijay",place:"TamilNadu",b:this.b};
    this.d = {name:"Vijay Sethupathi",place:"Namakkal",c:this.c};
}();
console.log(a);

Upvotes: 0

JLRishe
JLRishe

Reputation: 101652

You can't refer to an object before it exists, which is what you're trying to do. But you can do this:

var first = {
  a: 1,
  b: 'someString'
};

var container = {
  first: first,

  second: Object.assign({
      c: 34,
      d: 'something else'
    },
    first
  )
}

console.log(container)

Upvotes: 1

Related Questions