1
obj {
  val1 {
    nestedval {}
  }
  val2 {
    nestedval {}
  }
}

I want to access nestedval and want val1 or val2 as a variable i am trying like

var getVal = obj.varible.nestedval

but some how it's not working for me can anyone please help me to achieve this using angularjs. Thanks for your valuable time Guys.

5
  • Not releated to angular. You example is not a valid JS object. Can you please update. Please add your error message. Commented Aug 19, 2016 at 11:36
  • There's an article in W3School explaining object creation: w3schools.com/js/js_objects.asp Commented Aug 19, 2016 at 11:42
  • object structure I am trying to explain sorry if I missed any syntax error I am getting is Cannot read property 'nestedval' of undefined while when I try to print "variable" it's showing exact val which I am passing Commented Aug 19, 2016 at 11:42
  • Also I am saying in angular because I am not sure how to use variable in expression so Commented Aug 19, 2016 at 11:44
  • Thank you @dfsq for restructuring Commented Aug 19, 2016 at 11:47

1 Answer 1

2

Providing that your object structure look like this (added : to make it valid):

obj = {
  val1: {
    nestedval: {}
  }
  val2: {
    nestedval: {}
  }
}

You can use bracket notation to refer property by variable name:

var variable = 'val2'
var getVal = obj[variable].nestedval
Sign up to request clarification or add additional context in comments.

Comments

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.