Discovering a key based on a value stored in a JSON-containing associative array

In my search, I have come across a few answers that are similar, but not quite what I need.

Within an array called SongList, which I will show with just 2 items for brevity, the first pair is a key and the second pair is some JSON data.

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 am looking to retrieve the key (song_1 or song_2) based on the value of the title.

My plan is to iterate through a temporary array containing i items. Each item in this array should match a key in the SongList, and I will store these keys (song_1, song_2) in a final array.

Answer №1

Your data is made up of nested objects, not an array. Employ the for in loop.

function getTitleIndex(title) {
    for (var item in MusicLibrary) {
        if (MusicLibrary[item].title === title) return item;
    }
    return false;
}

Implement the function like this:

getTitleIndex("The First Song"); //returns "song_1"
getTitleIndex("Not This One"); //returns false

Answer №2

Let's take a look at this demonstration.

let heroes = {
 first: {name:"Batman", powerLevel:5},
 second: {name:"Spiderman", powerLevel:7},
 third: {name:"Ironman", powerLevel:9}
};

for (key in heroes) {
    if (heroes[key].name === "Ironman") {
         console.log ("Key = " + key);
    }
}

If you are seeking Ironman, the output will correctly indicate third.

Answer №3

Gratitude to all for shedding light on my confusion regarding Arrays versus Objects, which was impeding my ability to search effectively. With the guidance provided here, I have managed to craft a solution that I am pleased to share:

(The question above outlines an object called SongList)

Below is the function I developed for saving the keys of the playlist within 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 retrieves the track names
   for (var k in SongList){
      if(SongList[k].title == playItem) keys.push(k);//this links track name to keys
    }
}
localStorage.setItem('storedKeys',keys); 
});

It appears to be fulfilling my current requirements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Locating a specific class element within a collection of buttons using JQuery

I am currently working on making two buttons function similar to radio buttons, allowing only one to be selected at a time. HTML <button class="button" value="purchase" name="selector_button_group"> Purchase </button> <button class=" ...

Consistent Failure: jQuery File Upload consistently aborts with the error message 'File upload aborted'

I'm currently utilizing the Blueimp File Upload Plugin to facilitate file uploads to a remote server. The HTML code snippet for the file upload input is as follows: <input id="fileupload" type="file" name="files[]" data-url="http://my-server-ip/u ...

Encountering an unexpected issue with $urlMatcherFactory during an AngularJS service unit test

I am seeking guidance on writing a proper unit test for a service using the jasmine framework and karma as the test runner. Below is the implementation in example-service.js: export default class ExampleService { constructor($resource, $http, $urlMatcher ...

Angular: Discovering and retrieving all images within a div container

I am on a quest to locate all image tags within a specific div. These image tags are nested within paragraph tags inside the div. I attempted to create a plunkr to accomplish this task, but unfortunately, I haven't had any success yet. If anyone is ab ...

What is the best method for effortlessly inserting multiple images into a web form that are sourced from a database?

Greetings, I am currently in the process of creating a page where users can view specific car details and related photos. At the moment, I am utilizing a SQL table to store the image paths and then manually assigning each path as an "ImageUrl" attribute to ...

Encountering a problem with a Vue component error stating "Unable to convert undefined or null to object"

Encountering an error message "Cannot convert undefined or null to object" with this VueJs Slider. You can see it in action on this website (It's the first component on the page). The slider's functionality is working fine, but I'm looking ...

As I iterate through a MySQL array, JavaScript is able to manipulate the initial displayed data

I'm struggling to achieve the desired outcome with my code. It seems that when I iterate through an array of data, JavaScript only works on the first echoed data. Here is a snippet of the code: <?php $ids = array(); ...

Import the contents of a *.data file into a growing array of structures that can dynamically expand

As a beginner in C programming, I am tasked with reading a *.data file into a dynamically expanding array of structures. Once this is done, the goal is to sort the data by value and print it in high to low order. While I have managed to implement the sorti ...

Finding All Initial Table Cells in jQuery

Is there a streamlined method for retrieving all td elements (cells) from every row within a specific table, or do I have to manually iterate through the collection myself? ...

Unlocking the Power of Transition: Effortlessly Submitting a Form Post

After the modal finishes fading out, I want my form to be submitted and sent to the email file "refreshform.php". However, currently after the modal fades out, the form does not submit or post anything to the PHP file for sending the email. It simply fades ...

require a global function that accesses a variable inside it

I am currently struggling with a piece of JavaScript code that is causing some difficulty for me. The code is located inside a function, and I am trying to access the soft_left and soft_top variable in other functions without much success. Below is the rel ...

Form containing no field names using the multipart/form-data format

Initially, I had an HTML form set up to send information to a nodejs backend. When attempting to add file uploads to the same form, I needed to modify the enctype from its default value (application/x-www-form-urlencoded) to enctype='multipart/form-da ...

What steps can I take to locate the Angular version within my project?

After setting up the Angular code on my local machine, I am now eager to find out the version of Angular used in the project. Can someone please share a convenient method to locate this information within the command prompt? ...

Using asynchronous file uploading with jQuery and ASP.NET for a seamless user experience

I recently came across an article on Async file upload in ASP.NET which you can find here. Although the process was working fine up until the .ashx file call, I encountered an issue where "context.Request.Files.Count" showed 0. Any help or suggestions wo ...

Tips for fixing flickering tables and bringing the scrollbar back to the top in your DataTable Forge viewer

Presently, I am working with a DataTable that consists of 100 rows and is being set up using lists. The lists dynamically change based on the selected name from a drop down. To achieve this, I use: $("#datatable").remove(); this.datatable = new Au ...

The issue with ui-router failing to render the template in MVC5

I'm having trouble setting up a basic Angular UI-Router configuration. My goal right now is to have a hardcoded template render properly, and then work on loading an external .html file. My project is using MVC5, so I'll provide the necessary fi ...

Performing a $lookup operation across various collections for a nested output

I have multiple collections and I've utilized the separate collection & foreign key approach. Now, I'm looking to combine these collections to create nested collections. Take a look at my collection schemas: const SurveySchema = new Schema({ _id ...

Converting month names to uppercase with moment.js

After changing the moment's locale by setting the property below: moment.locale(chosenLocale); It appears that everything is functioning correctly. The month names and weekday names are displayed according to the selected locale, and week numbers ar ...

Utilizing regular expressions to search through a .md file in JavaScript/TS and returning null

I am currently using fs in JavaScript to read through a changelog.MD file. Here is the code snippet: const readFile = async (fileName: string) => { return promisify(fs.readFile)(filePath, 'utf8'); } Now I am reading my .md file with this fu ...

The Cordova Android app is experiencing issues with Ajax requests

While testing my project on the Chrome browser, the AJAX requests were functioning properly. However, upon installing the app on an Android device, the requests stopped working altogether. Below is the code snippet used: var xhr = new XMLHttpRequest() ...