0

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?

CaribouCode
  • 13,998
  • 28
  • 102
  • 174

1 Answers1

1

what about this?

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

var test = function(field, keyname){
  return obj[field][keyname];
};
Alexander_F
  • 2,831
  • 3
  • 28
  • 61
  • Yes this will work, except what if the object had more layers and I wanted to use the function to target any layer of the object? – CaribouCode Nov 25 '15 at 11:06
  • in this case you can write a function and work with "arguments" http://www.w3schools.com/js/js_function_parameters.asp javascript allowing you to pass N number on parameters to the function – Alexander_F Nov 25 '15 at 11:08