0

Can i duplicate JSON property during initialization in javascript like the example below

var obj = { 
prop1: {...},
prop2: prop1 
}

EDIT: Looks like my data structure was designed poorly in the first place, however the solutions below work in this case.

user3413046
  • 109
  • 1
  • 13

3 Answers3

0

You can't do it in one step, you have to do with:

var obj = { 
  prop1: {...}
};

obj.prop2 = obj.prop1;

Note obj.prop2 and obj.prop1 refs the same object in this case.

xdazz
  • 158,678
  • 38
  • 247
  • 274
0

Another work around would be to add prop2 and declare it as undefined, then add a setProp function on your object that can set the property for you.

var obj = {
    prop1: {someValues: [], someValue: {}},
    prop2: undefined,
    setProp2: function(){
        this.prop2 = this.prop1;
    }
};

Maybe it is possible for you to make a small function that makes an instance of the object and calls the setProp2?

Not sure this is what you are after. If you can supply what you want to use it for then it might be easier to supply a different approach.

David
  • 104
  • 6
0

Why would you imagine that prop1 in prop2: prop1 would have any meaning other than the value of the variable prop1, which does not exist? An object is not a function. Object properties are not function variables.

You could try prop2: this.prop1, but that would betray a fundamental misunderstanding of the meaning of this. See Self-references in object literal declarations.

If you want to set two properties to the same value, then just do so:

var obj = (function() {
  var prop1 = {someValues: [], someValue: {}};
  return {
    prop1: prop1,
    prop2: prop1
  };
}());
Community
  • 1
  • 1