Jump to content
antidot

Question about accessing objects...

Recommended Posts

// four variables are created and assigned in a single go, 
// separated by commas
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);

function showProps(obj, objName) {
  var result = "";
  for (var i in obj) {
    if (obj.hasOwnProperty(i)) {
      result += objName + "." + i + " = " + obj[i] + "\n";
    }
  }
  return result;
}

Ok. That's a code example from mdn: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

 

now I am wondering if using the showProps function, how to access

1. the "date created" property (or any prop with spaces)

2. the "rand" property (or any prop with number)

 

myObj["date created"] shows correctly.

myObj["object Object"] how to access ?

myObj[rand] works because the key name is stored in that var...

 

when using the the function passing "date created" won't work. Or any other spaced string. It shows undefined or throws error of mmissing "]" even its present....

 

So i wonder how to acces all the properties correctly. Is it even possible tow access them somehow by index as in an array? Because the property name for "rand" of course results in a random number...

 

 

Share this post


Link to post
Share on other sites


<script>

var myObj = {

str: "myString",

rand: Math.random(),

obj: {},

type: "Dot syntax",

date_created: "String with space"

}

myObj.str = "String value";

alert(myObj.str);

myObj.rand = "Random Number";

alert(myObj.rand);

myObj.obj = {objstring: "Even an empty string"};

alert(myObj.obj.objstring);

</script>

Share this post


Link to post
Share on other sites

You access the property exactly the way it shows:

 

myObj["date created"]
If you have a number or other value in a variable, then you can use the variable also:

 

myObj[var]

Is it even possible tow access them somehow by index as in an array?

Yes, that is exactly what those examples show. You can use dot syntax if the property name is a valid identifier, or else you use array syntax.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...