ken
ken

Reputation: 286

javascript objects or arrays? what is this?

function(property, res, err, result){
    var json = {};
    json[property] = result;
    res.json(json);
};

Okay, this is a function that will take the above parameters. When invoked it creates an Object called json, my question is about the next line I dont understand it at all, is the object then the list of properties? Please enlighten me.

Upvotes: 1

Views: 45

Answers (2)

Alexandr Lazarev
Alexandr Lazarev

Reputation: 12882

You are just setting the property of the object. Object properties can be accessed/set in different ways:

objectName.property          // person.age

or

objectName["property"]       // person["age"]

or, your case:

objectName[expression]       // x = "age"; person[x]

Upvotes: 3

Sam
Sam

Reputation: 1125

There are 2 ways to set the properties on objects. Most times people use dot notation like this:

json.property = result;

But if the property name is a string (which is what will be passed in as the property argument), the way the object property is set is like this:

json[property] = result

For example if someone puts these arguments into the function ("name", blah, blah, "Sam"), what is actually happening in the line in question is:

json["name"] = "Sam"

Which is equivalent to:

json.name = "Sam"

And results in an object named json that looks like this:

{
  name: "Sam"
}

Upvotes: 4

Related Questions