0

I have a issue with javascript. Please take a look:

    function Component(data)
    {
       var self = this;

       self.Name = data.name;
    }

    function Testing() {
        var self = this;

        self.Components = [
        {
            A: new Component({
                name: 'test1'
            })
        }, {
            B: new Component({
                name: 'test2'
            })
        }, {
            C: new Component({
                name: 'test3'
            })
        }];
    }

Now what i am trying to do is, I want to access each component from Components array by its property name (A, B ,C ...). So for this i did and getting error:

var t = new Testing();

t.Components['A'].Name; ==> //Error: Cannot read property 'Name' of undefined      

Whats the issue ?

1
  • Without changing the structure, you have an array of objects, so you'd have to access the values with t.Components[0]['A'].Name, t.Components[1]['B'].Name, etc. But using an object instead of an array of objects makes more sense here. Commented Aug 11, 2013 at 9:38

2 Answers 2

3

To access the properties of Component using a key self.Components must be an object (associative array). The code attempts to access the array using a key, which is fine for associative arrays, but will not work for a regular array as declared in the code. Switching self.Components to an object literal will allow the properties to be accessed by key.

function Testing() {
    var self = this;

    self.Components = {

        A: new Component({
            name: 'test1'
        }), 
        B: new Component({
            name: 'test2'
        }), 
        C: new Component({
            name: 'test3'
        })
    };
}

JS FIDDLE: http://jsfiddle.net/fxfbe/

Sign up to request clarification or add additional context in comments.

2 Comments

@T.J. Crowder Thanks for picking up those syntax errors. Just woke up a few minutes ago!
@ Kevin: Not a problem
1

The problem is that Components defined in the Testing is an array, remove array and create simply as object..

function Testing() {
....
    self.Components = {
        A: new Component({
            name: 'test1'
        }),
        B: new Component({
            name: 'test2'
        }),
        C: new Component({
            name: 'test3'
        })
    };
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.