/    Sign up×
Community /Pin to ProfileBookmark

Grab JSON element with function

Hi –

I have existing JSON object on the page and I’m trying to call a value from the object using a function:

[CODE]

var DDO = {};
DDO.specVersion = “10-1-2014”
DDO.navData = {
“home”:”Home Page”,
“news”:”News”,
“music”:”Music”,
“video”:”Video”,
“shop”:”Shop”,
“tour”:”Tour”,
“fanwall”:”Fan Wall”,
“social”:”Social”
};
[/CODE]

I have a simple function designed to return any value of the object:

[CODE]

function grab_navData(elm)
{
var navElement = DDO.navData.elm;
return navElement;
}

[/CODE]

I call the function like so:

[CODE]

grab_navData(‘social’);

[/CODE]

Running this function returns no errors but returns undefined – instead of the value of “Social” like I would expect. And if I choose to write out the direct path to the element as a test

[CODE]

var navElement = DDO.navData.social;

[/CODE]

the code returns as expected.

I’m trying to figure out if this is a scope issue inside the object or if I need to convert the value of (elm) to an object first.

Any ideas would be helpful.

Thanks

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@Sup3rkirbyOct 27.2014 — I forget why, but when you are trying to dynamically call a variable name you must do it inside of square brackets ([B][ ][/B]).
[CODE]
function grab_navData(elm) {
var navElement = DDO.navData[elm];
return navElement;
}
[/CODE]
Copy linkTweet thisAlerts:
@SalemBlueauthorOct 29.2014 — @Sup3rkirby That's it. Can't use dot notation when referencing a dynamic element.

Thanks for the response.
Copy linkTweet thisAlerts:
@Troy_IIIOct 31.2014 — DDO.navData.elm; will ask for "elm" property of "navData" literaly. [which is 'undefined']

DDO.navData[elm]; will pass the 'elm' value for asked property of "navData" which happens to be an existing token "social" representing a presently defined property of "navData" as if it was literally written like: DDO.navData.social;
×

Success!

Help @SalemBlue spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...