我搜索并找到了一些相似但不完全的答案。
我有一个数组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"}
...
};
Run Code Online (Sandbox Code Playgroud)
我希望能够检索给定值中的键(song_1或song_2)title。
我将循环遍历一个临时i项目数组,该数组中的每个项目都会有一个匹配项SongList,并且我会将键 ( song_1, song_2) 保存在最终数组中。
你没有一个数组,你有一个包含更多对象的对象。使用for in
function findTitle(title) {
for (var key in SongList) {
if (SongList[key].title == title) return key;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
然后调用它!
findTitle("title of first song"); //returns "song_1"
findTitle("BNOT MEEEEEE"); //returns false
Run Code Online (Sandbox Code Playgroud)