Question

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.

Was it helpful?

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();

OTHER TIPS

Well, arrays are numeric-based, so

someArray["customProp"]: 0

wouldn't work. It should be a Javascript Object {} for string-based keys to work. And then you could just say

someArray: {0:"one",1:"two","customProp":0},

For your second question: I don't think that's possible. The object is not yet initialized, so you can't yet read out of it...

You can set properties on the Array but they will not get iterated using native functions. Your alternatives are an object (as suggested) or an array with an object as one of the members:

["one", "two", {customProp: 0}]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top