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?

7
  • test("field1.name"); would mean obj["field1.name"]; Commented Nov 25, 2015 at 11:00
  • return obj[field] && obj[field].name; Commented Nov 25, 2015 at 11:02
  • @Ramanlfc Yes I'm well aware of that. Hence why I said it doesn't work and am asking what is the correct way to do this. Commented Nov 25, 2015 at 11:02
  • 2
    Is this what you want to achieve? stackoverflow.com/questions/6491463/… Commented Nov 25, 2015 at 11:08
  • Possible duplicate of Convert string in dot notation to get the object reference Commented Nov 25, 2015 at 11:10

1 Answer 1

1

what about this?

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

var test = function(field, keyname){
  return obj[field][keyname];
};
Sign up to request clarification or add additional context in comments.

2 Comments

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?
in this case you can write a function and work with "arguments" w3schools.com/js/js_function_parameters.asp javascript allowing you to pass N number on parameters to the function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.