简体   繁体   中英

Find key from value in associative array containing JSON

I've searched and found a few similar-but-not-quite answers.

I have an array SongList (showing 2 items for brevity...) - the first pair is a key, the second pair is some JSON.

SongList={
    song_1:{title:"title of first song",artist:"the artist",mp3:"http://mysite/song1.mp3"},
    song_2:{title:"title of second song",artist:"the artist",mp3:"http://mysite/song2mp3"}
    ...
};

I would like to be able to retrieve the key ( song_1 or song_2 ) given the title in the value.

I will be looping through a temporary array of i items, each item in this array would have a match in SongList and I would save the key ( song_1 , song_2 ) in a final array.

You don't have an array, you have an object, containing more objects. Use for in

function findTitle(title) {
    for (var key in SongList) {
        if (SongList[key].title == title) return key;
    }
    return false;
}

And then call it!

findTitle("title of first song"); //returns "song_1"
findTitle("BNOT MEEEEEE"); //returns false

Here is an example.

var one = {
 a: {b:"MightyMouse", d:2},
 b: {b:"MickeyMouse", d:4},
 c: {b:"Superman", d:6}
};

for (outerkey in one) {
    if (one[outerkey].b === "Superman") {
         console.log ("Outerkey = " + outerkey);
    }
}

Assuming you are looking for Superman , this prints as expected c .

Thanks everyone, I realize my understanding of Arrays v. Objects was an issue which obviously hindered my Google-Fu. I hope it's ok to post the answer I finally arrived at via guidance here:

(SongList object is described in question above)

This is the eventual function I arrived at for saving the keys of the playlist SongList:

$("#save_playlist_as_keys").click(function() {
var keys = []
for(var i=0; i<myPlaylist.playlist.length; i++){
   var playItem = (myPlaylist.playlist[i].title); //this returns the names of the tracks
   for (var k in SongList){
      if(SongList[k].title == playItem) keys.push(k);//this matches track name to keys
    }
}
localStorage.setItem('storedKeys',keys); 
});

This seems to be doing what I want for now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM