简体   繁体   English

从包含JSON的关联数组中的值中查找键

[英]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 (为简便起见,显示2个项目...)-第一个对是键,第二对是一些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. 我希望能够根据值中的title检索键( song_1song_2 )。

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. 我将遍历i项的临时数组,该数组中的每个项在SongList都会有一个匹配项,并且我会将键( song_1song_2 )保存在最终数组中。

You don't have an array, you have an object, containing more objects. 您没有数组,有一个对象,其中包含更多对象。 Use for in 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 . 假设您正在寻找Superman ,这将按预期打印c

Thanks everyone, I realize my understanding of Arrays v. Objects was an issue which obviously hindered my Google-Fu. 谢谢大家,我意识到我对Arrays v。Objects的理解是一个明显阻碍我的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) (上面描述了SongList对象)

This is the eventual function I arrived at for saving the keys of the playlist SongList: 这是我最终用来保存播放列表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. 这似乎正在做我现在想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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