In general, when you have an object with named keys (obtained from JSON data or elsewhere), you're not likely to want to iterate over those keys. It's more likely that you will want to reference those keys specifically by name. After all, a store
is a very different thing from a manager
, isn't it?
In most cases it wouldn't make much sense to write a loop (or equivalent such as $.each()
) where you iterate over both stores and managers and do the same thing with them. You probably want to do one thing with stores, and a different thing with managers.
OTOH, with the specific data you have here, a store record does look a lot like a manager record. Each one has a name; the difference is that a store has an skey
and a manager has an mkey
. So just for the purposes of logging your data, you could do something like this (fiddle):
var data = {
"store": [
{ "skey": "asdsad123das", "name": "Store1" },
{ "skey": "3308d976d264", "name": "joji store" }
],
"manager":[
{ "mkey":"asdsad123das", "name":"manager 1" },
{ "mkey":"asdsad123da2", "name":"Manager 2" },
{ "mkey":"asdsad123da3", "name":"Manager 3" }
]
};
function success( data ) {
list( data.store, 'skey' );
console.log( ' ' );
list( data.manager, 'mkey' );
function list( array, key ) {
$.each( array, function( i, item ) {
console.log( item[key], ':', item.name );
});
}
}
success( data );
Note that we use data.store
and data.manager
to access each of the two individual arrays. (And I called it data
instead of msg
because msg
sounds like an abbreviation for "message", and this does not seem to be a message of any kind.)
But since the arrays themselves are similar, I used a common function to log each of them. That function takes a parameter telling it whether to use the skey
or mkey
.
In real code working with this data, you may find that what you do with a manager
is so different from what you do with a store
that you won't even have this much common code between them. But once you're able to access that data reliably you can figure it out from there.
Now the most important tip: Do you know how to use the JavaScript debugger in your favorite browser? I recommend the one built into Chrome, but there is also FireBug for Firefox and the built-in debugger in Internet Explorer.
If you add a debugger;
statement to your code and load your page with the debugger open, it will stop on that line of code, and then you can look at the variables in the locals/watch panels, and you can use the console to try out different expressions to see what they do. You can also single-step through your code, step into functions, etc. You won't need to use alert()
any more; you'll find this a much superior way to debug your code.
Here is information on the Chrome developer tools. If you haven't used these debugging tools before, you should seriously stop everything else you're doing and get familiar with them. It will pay off immensely.