javascriptobjectpropertiesobject-notation

How To Set a Property's Property While Creating the Object


I have an object and one of the properties is an array. I want to set a new property on that array (customProp = 0). However, I want to do so inside myObject's declaration.

myObject = {
  someString: "text",
  someArray: ["one","two"],
    /* What I've Tried */
    someArray: { customProp: 0 } // Overwrites my array with a new object
    someArray["customProp"]: 0 // Invalid syntax
    someArray: customProp: 0 // Also invalid
}

If I can't create the array then set a property on it, can I do so in one fell swoop (again, staying within the confines of this object)?



I have another (small) question: How can I reference one of the properties still inside the declaration. I want to set otherProp = someString, how would I do so?

myObject = {
  someString: "text",
  otherString: someString, // someString is undefined
  otherString: myObject["someString"], // myObject is undefined
  otherString: this["someString"] // Just... undefined
}

I may need to split this into a separate question, but hopefully whoever answers the first will know the answer to the second.


Solution

  • Unfortunately neither of your requests are possible. Object literals in JavaScript are convenient but come with drawbacks, mostly what you've discovered.

    When you are inside an object literal, the object doesn't quite exist yet. The JavaScript interpreter hasn't finished ingesting it. So inside the literal, this points to the object just outside the literal, and the literal has no way to refer to other parts of itself.

    Fortunately, you can do both of what you want by just doing it after the literal declaration.

    myObject = {
        someString: 'text',
        someArray: ['one', 'two']
    };
    
    myObject.someArray.customProp = 0;
    myObject.otherString = myObject.someString;
    

    Or if you want, you can wrap all of this inside a constructor function and create your object with new.

    function MyObject() {
        this.someArray = ['one', 'two'];
        this.someArray.otherProp = 0;
        this.otherString = this.someString = 'text';
    }
    
    var myObject = new MyObject();