Bass
Bass

Reputation: 23

Javascript - "concatenate" with a variable in a for loop

I am not really sure about the therm I use in my title, but here we go.

So I have something like that:

for (var key in myObject) {

var GivenName = theObject.PS_1.GivenName;
var GivenName = theObject.PS_2.GivenName;
var GivenName = theObject.PS_3.GivenName;
var GivenName = theObject.PS_4.GivenName;
// and so on...

}

So obviously I don't wanna write everything like that, I need to use the var Key, but I didn't figure how the hell I am supposed to do that, I tried alof of thing, but I failed everytime, yes I'am bad and I should feel bad.

I tried this:

var GivenName = 'theObject.'+key+'.FirstName';
var GivenName = theObject.key.FirstName;
var GivenName = theObject.[key].FirstName;
var GivenName = theObject.['key'].FirstName;
var GivenName = theObject.[+key+].FirstName;

btw the Key var contain PS_1 then PS_2 then PS_3...

Upvotes: 2

Views: 1775

Answers (3)

dm03514
dm03514

Reputation: 55952

If you haven't had a chance to read it yet the mozilla javascript documentation is absolutely awesome. https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects

Even if you are familiar with most of it it will still provide excellent reference info. From the docs:

Object properties names can be valid JavaScript string, or anything that can be converted to string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has space or dash, or starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime). Examples are as follows:

var myObj = new Object(),
    str = "myString",
    rand = Math.random(),
    obj = new Object();

myObj.type              = "Dot syntax";
myObj["date created"]   = "String with space";
myObj[str]              = "String value";
myObj[rand]             = "Random Number";
myObj[obj]              = "Object";
myObj[""]               = "Even an empty string";

console.log(myObj);

Upvotes: 1

Marc B
Marc B

Reputation: 360592

var GivenName = theObject[key].FirstName;

Upvotes: 2

I Hate Lazy
I Hate Lazy

Reputation: 48761

for (var key in myObject) {
    var value = myObject[key];
}

http://eloquentjavascript.net

Upvotes: 1

Related Questions