2

I have a json object and a property of which is a nested json. The nested json has a function as a property. I want to access a property in that outer json from that function in that inner json.

Let me explain with a dummy code,

{
  name: "Barry Allen",
  getName: function () { 
      return this.name; //this is returning "Barry Allen", which is fine
    },
  nestedJson: {
    getName: function () {
      //here I want something like return this.parent.name
    }
   }  
}

I want to access name from getName of nestedJson. Is it possible? Is there any parent child traversing mechanism/way in json and nested json objects in javascript?

Thanks in advance.

3
  • 1
    stackoverflow.com/questions/2001449/… Commented May 18, 2016 at 14:28
  • 3
    This is not JSON, JSON doesn't support functions. This is a JavaScript object. Commented May 18, 2016 at 14:28
  • Sorry, I did not know that Commented May 18, 2016 at 14:47

1 Answer 1

4

This is a POJO (Plain Old JavaScript Object), not JSON.

The context of this inside nestedJson.getName() is different than the context of this inside the first-level .getName(). Since this object will already be defined by the time this function exists, you can use the object itself as a replacement for this.

var person = {
   name: "Some Guy",
       getName: function () { 
       return this.name;
   },
   nested: {
       getName: function () {
           return person.name;
       }
   }  
};

var try1 = person.getName();
var try2 = person.nested.getName();

console.log('try1', try1);
console.log('try2', try2);

That being said, I'd turn this into a different type of object. Read this: http://www.phpied.com/3-ways-to-define-a-javascript-class/

Sign up to request clarification or add additional context in comments.

2 Comments

Nice Approach. One thing, this inside nested.getName() should be whatever on the left side of getName(), in this case, it is nested object, not window
Thanks for the answer @Mike, Also thanks for the link, I will read it. But changing the object structure is not in my hand. I didn't write it :P

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.