0

I cannot seem to find an answer to this and I am confused.

I have the following set up:

var object1 = {
    array1: [
        {
            prop1: val1,
            prop2: val2
        },
        {
            prop1: val1,
            prop2, val2
        }
    ]

}

My question is, when I add "prop3" I want to refer to prop1 and prop2. I thought I could use this as in the below example but it doesn't work.

var object1 = {
    array1: [
        {
            prop1: val1,
            prop2: val2,
            prop3: "I want to include " + this.prop2 + " in this string"
        },
        {
            prop1: val1,
            prop2, val2
        }
    ]

}

I tried this because I'm aware that accessing a property within an object works using the this keyword.

However this.prop2 evaluates as undefined. I presume that this may not be the whole problem. As when I try:

var object1 = {
    array1: [
        {
            prop1: val1,
            prop2: val2,
            prop3: "I want to include " + object1.array1[0].prop2 + " in this string"
        },
        {
            prop1: val1,
            prop2, val2
        }
    ]

}

With this code I get an error "cannot read property array1 of undefined". However when I take it out the string, so the rest of my js runs okay, and console.log(object1.array1[0].prop2, i get, as expected, val2.

Thanks

Mike
  • 254
  • 1
  • 6
  • 16
  • It is in fact duplicate question. Anyway following may work for you. var object1 = { array1: [ { prop1 : 13, prop2 : 15, }, { prop1 : 13, prop2 : 12, }, ], init: function() { this.array1[0].prop3 = "I want to include " + this.array1[0].prop2 + " in this string"; return this; } }.init(); alert(object1.array1[0].prop3); – 01000001 Mar 16 '17 at 17:17
  • @Arpit thanks. This will work. Appreciate your help. – Mike Mar 17 '17 at 08:10

0 Answers0