1

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?

bsky
  • 19,326
  • 49
  • 155
  • 270

4 Answers4

1

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)
JLRishe
  • 99,490
  • 19
  • 131
  • 169
1

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)
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
0

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);
Vignesh Raja
  • 7,927
  • 1
  • 33
  • 42
0
var container = {
    first: {
        a: 1,
        b: 'someString'
    }
}

container.second = Object.assign(
    {
        c: 34,
        d: 'Something else'
    },
    container.first
)
  • You might want to elaborate on what you changed and why this is solving the problem. – empiric Jan 11 '18 at 12:00
  • 3
    While this code snippet may be the solution, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-‌​code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – yivi Jan 11 '18 at 14:35