0

I'm trying to get the value of an array/object by passing KEY that is splitted from data attribute.

Please take a look of this whole scenario.

1st - passing the data-* to an element

 <a data-action='{"content":"content.login"}' ... >val</a>

2nd - get the data attribute value

 var da = ele.data("action");
 var c = da.content;
 var c0 = c.split('.')[0];
 var c1 = c.split('.')[1];

4th - array/obj

 var content = {
    login : "..."
 };

3rd - trying to get the val of array

 console.log(c0[c1]);

result - undefined

Can someone give me the solution so that it logs the exact value of content.login by simply calling c0[c1]?

1
  • c0 suposed to be a string like "content", right? So this can't work c0[c1]... Commented Jan 22, 2015 at 10:42

2 Answers 2

1

You can call the variable using the string by passing it to window: window[c0][c1]

var content = {
   login : "awesome"
};

var data = $('div').data('data');
var c = data.content;

var c0 = c.split('.')[0];
var c1 = c.split('.')[1];

console.log(c0, c1);

alert(window[c0][c1]); 
   // translates to window['content']['login'] => calls content.login
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div data-data='{"content":"content.login"}'></div>

NOTE: If you are in a function closure you can use this instead of window.

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

3 Comments

its working great. But please can u explain the concept behind window.
Window is an object that contains DOM elements, functions/methods, events and the variables you create. It's basically the parent of everything. You can find what it has here
When you for example call the variable c the you are actually calling window.c but the window part is not mandatory anymore since it's build in with the browser.
0

You're doing assignment of a single element rather than of array:

var c0 = c.split('.')[0]; //Take 1st element of array

So you can't try to access element of array like you have:

c0[c1]

Just print c0.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.