CaribouCode
CaribouCode

Reputation: 14398

Javascript - get object value using variable

I'm trying to get an object value by passing a variable to a function, but I'm not sure how to do this with a multi layer object. It looks like this:

var obj = {
  field1: { name: "first" },
  field2: { name: "second" }
};

var test = function(field){
  //sorting function using obj[field]
  //return results
};

With the above, the following works:

var result = test("field1");

This sorts using the object {name: "first"} but say I want to use just the name value. I can't do this:

var result = test("field1.name");

What is the correct way to do this?

Upvotes: 0

Views: 86

Answers (1)

Alexander_F
Alexander_F

Reputation: 2879

what about this?

var result = test("field1", "name");

var test = function(field, keyname){
  return obj[field][keyname];
};

Upvotes: 1

Related Questions