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,156
  • 22
  • 91
  • 166

1 Answers1

1

what about this?

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

var test = function(field, keyname){
  return obj[field][keyname];
};
Fribu - Smart Solutions
  • 2,734
  • 3
  • 27
  • 60
  • 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 – Fribu - Smart Solutions Nov 25 '15 at 11:08