3

First of all, forgive me if I didn't identify the right type of array, however I can't seem to figure this out.

I'm trying to run this array in query:

var myArray = {"artists":[{
            "a1":"Adam Sandler",
            "a2":"Adam Lambert",
            "a3":"Avril Levine",
            "a4":"Backstreet Boys",
            "a5":"Blackstreet",
            "a6":"Black Eye Peas",
            "a7":"Cool and the Gang",
            "a8":"Chicago",
            "a9":"Charlie Manson"

        }],
        "songs":[{
            "s1":"Grow Old With You",
            "s2":"Whatdaya Want From Me",
            "s3":"Yea yea",
            "s4":"Quit Playing Games With My Heart",
            "s5":"No Digity",
            "s6":"Meet Me Half way",
            "s7":"Doo wa ditty",
            "s8":"Fight for your honor",
            "s9":"Charlies Song"
        }],
        "genre":[{
            "g1":"Pop",
            "g2":"Pop",
            "g3":"Alternative",
            "g4":"R & B",
            "g5":"R & B",
            "g6":"Hip-Hop",
            "g7":"Funk",
            "g8":"Soft Rock",
            "g9":"Rock"
        }]};

When I click a button (say for title) I don't know how to have it automatically go through the array. This is what I have for my button:

                $.each(myArray.songs, function(e,i){
                    console.log("e:"+e+" - i:"+i+" - "+myArray.songs[e].i);

                });

This does work, however when it reaches to the console.log, this is what I get:

e:0 - i:[object Object] - undefined

I don't know how to get "i" to work, it always gives me [Object Object]. I replace I with the actual id in the array, it works.

Thank you.

4
  • These arrays are very strange. Each one has only one item Commented Mar 26, 2013 at 1:50
  • 1
    It's not entirely clear what you're trying to accomplish here. Can you be more specific about the expected output? Commented Mar 26, 2013 at 1:55
  • @Tharsan, I was just trying to go display all the stuff in the songs object. Commented Mar 26, 2013 at 2:20
  • @tjb1982, please explain why this is strange. I'm still learning this, so your info is greatly apprecaited. Commented Mar 26, 2013 at 2:21

5 Answers 5

14

If you want to use $.each you can try this:-

$.each(myArray.songs, function (i, ob) {
    $.each(ob, function (ind, obj) {
        console.log("key:" + ind + " value:" + obj);
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

This totally worked! Thank you all for your input, I'm jsut learning JSON, so I apologize if this confused everyone or if it's not used right. I wasn't being thrown an errors, so I assumed it was fine.
1

If you are trying to loop through all of the songs, myArray.songs is an array with one object in it.

Try this:

$.each(myArray.songs[0], function(e, i) {
  console.log('e:' + e + ' - i:' + i);
});

And check out this jsFiddle http://jsfiddle.net/TsJP5/1/.

1 Comment

This also worked for me too!! You guys are super awesome for your help!
0

Your structure is a bit strange - songs is an array with a single json element containing your key - value pairings. Nonetheless, to loop over these elements you should do:

    var songsElement = myArray.songs[0];
    for (var key in songsElement) {
        if (songsElement.hasOwnProperty(key)) {
            console.log(key + " -> " + songsElement[key]);
        }
     }

Comments

0

Unless you need to iterate a collection of jQuery elements, I wouldn't use $.each() (this is personal preference). Rather, exploit the native forEach() method on Array:

function each(obj, onSuccess, recursive) {
    if (obj && (typeof obj === 'object' || typeof obj === 'array')) {
        Object.keys(obj).forEach(function(key) {
            var val = obj[key];
            if (onSuccess && val && key) {
                var quit = onSuccess(val, key);
                if (false === quit) {
                    return false;
                }
            }
            if (true === recursive) {
                each(val, onSuccess, true);
            }
        });
    }
}

This handles both Array and Object instances as well as recursion. You take a slight performance hit by always using Object.keys() to get the member names, but I think its ultimately negligible even on very large data sets.

1 Comment

Not all browsers support .forEach so you might have to modify the array prototype in order to use it like this: if (!('forEach' in Array.prototype)) Array.prototype.forEach = function() { ... }; see stackoverflow.com/questions/8348569/… for implementation details
0

I'm not completely sure what your data means, but it looks like a bunch of song/artist/genre groupings that go together. E.g.,

[{"song":"Losing My Religion",
  "artist":"R.E.M.",
  "genre":"alternative"},
 {"song":"Bizarre Love Triangle",
  "artist":"New Order",
  "genre":"electronica"}]

I'm not sure why s1, a1 or g1 are useful, so I'm leaving them out. And then I honestly think using jquery for this isn't helpful. I would do this instead:

for (var i = 0; i < myArray.length; i++)
  console.log(myArray[i].song + " by " + myArray[i].artist + " is of the " + myArray[i].genre + " ilk.");

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.