Tips for accessing the attribute of a JSON object in JavaScript that includes the '#' symbol in the key

When I receive the JSON object from the last.fm API, it looks like this:

{
    "artists": {
        "artist": {
            "name": "Daft Punk",
            "playcount": "494599",
            "listeners": "106101",
            "mbid": "056e4f3e-d505-4dad-8ec1-d04f521cbb56",
            "url": "http://www.last.fm/music/Daft+Punk",
            "streamable": "1",
            "image": [
                {
                    "#text": "http://userserve-ak.last.fm/serve/34/5463.jpg",
                    "size": "small"
                },
                {
                    "#text": "http://userserve-ak.last.fm/serve/64/5463.jpg",
                    "size": "medium"
                },
                {
                    "#text": "http://userserve-ak.last.fm/serve/126/5463.jpg",
                    "size": "large"
                },
                {
                    "#text": "http://userserve-ak.last.fm/serve/252/5463.jpg",
                    "size": "extralarge"
                },
                {
                    "#text": "http://userserve-ak.last.fm/serve/500/5463/Daft+Punk.jpg",
                    "size": "mega"
                }
            ]
        },
        "@attr": {
            "page": "1",
            "perPage": "1",
            "totalPages": "1000",
            "total": "1000"
        }
    }
}

I want to extract the image URLs from the object, but the key for the URLs is "#text". I'm not sure how to access a value with "#" in the key using Javascript. I am currently using AngularJS, but suggestions using plain JavaScript would be helpful as well. Does anyone know how I can retrieve the value associated with "#" in the object key?

Any guidance on this issue would be highly appreciated.

Thanks!

Answer №1

If the data is stored in the obj variable, you can extract an array of images using the following code snippet:

var imgSrcArray = obj.artists.artist.image.map(function(image){ return image['#text'] });

In ES6:

const imgSrcArray = obj.artists.artist.image.map( image => image['#text'] );

That's all there is to it.

If you prefer a more traditional approach to looping through this array, you can use the following code:

var images = obj.artists.artist.image;
for(var i=0; i < images.length; i++){
   var image = images[i];
   var url = image['#text'];
   console.log("url: ", url);   //Displays the image URL
}

Cheers!

Answer №2

bar['bands']['musician']['picture'][0]['#text']

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

Merge nested arrays while eliminating any redundant elements

Is there a way to merge these array sets while ensuring that duplicate values are removed? I am unsure if lodash provides a solution for this specific scenario where the arrays are nested. Most of the solutions I have come across assume flat arrays. Any ...

Ways to adjust the size of the parent element based on the height of a specific element

I am faced with a situation where I need to identify all elements belonging to a specific class and adjust the padding-bottom of their parent div based on the height of the matched element. For example, consider the following structure: <div class=&ap ...

Having trouble implementing String.prototype in my factory

Currently, I am working on incorporating a function mentioned in this answer. String.prototype.supplant = function (o) { return this.replace(/{([^{}]*)}/g, function (a, b) { var r = o[b]; return typeof r === 's ...

Transform the string array into a single string before performing serialization

This is a snippet from my code: Dictionary<string, string[]> dict = new Dictionary<string, string[]>(); I have populated my dictionary with data, and I am serializing it using: JsonConvert.SerializeObject(dict) My goal is to convert string[ ...

What is the best way to save user input from an HTML text field into a jQuery variable for long-term storage?

JavaScript with jQuery $(document).ready(function(){ var userGuess; $('#submit').on("click", function() { userGuess = $('#guess-value').val(); $("#value").text(userGuess); alert(userGuess); }); ...

The basic node API request is not showing any information

There is a request in my server.js file var Post = require('./../models/post'); //GET ALL POSTS app.get('/api/posts', function (req, res) { Post.getPosts(function (err, posts) { if(err) { throw err; } ...

What are some methods for extracting a value from a separate webpage and saving it as a variable in my code?

I am utilizing graphite to obtain statistics and would like to display a justgage gauge for a specific variable. Graphite provides values in either JSON format: [{"target": "snmp.ssbSubstation.realEnergy.1", "datapoints": [[4511552439.0, 1417540920]]}] o ...

Exploring the capabilities of Google Maps APIv3 with managing numerous markers

I have been experiencing an issue with my code related to zLat and zLng. I noticed that when I substitute zLat and zLng with tLat and tLng inside the for loop, I can see one marker displayed on the map. However, if I use zLat and zLng, no markers show up. ...

When switching between activities in ANDROID STUDIO, the local json file keeps resetting

I have encountered a problem with my Android app. In my second activity, I am reading and modifying a local JSON file. Everything works as expected until I switch back to the mainActivity and then return to the second activity. It appears that the changes ...

The Ionic v1 modal is being destroyed prematurely, interrupting the leave animation before it

While using the default slide-in-up animation for an Ionic (v1) modal, the leave animation works flawlessly. However, when I switch to a different animation (specifically, slide-in-right), the modal is being destroyed (i.e., removed from the DOM) before th ...

How can I format the input type number with a thousand separator as 123.456.789?

When entering the number 123456, I want to see 123.456 displayed in the input field. I tried using my code, but it displays 123,456 instead. Is there a way to ensure that the thousand separator is a dot and not a comma? You can view my code at this link ...

The Node.js response triggers an error message stating: 'SyntaxError: JSON.parse: unexpected end of data.'

My attempt to establish a connection between Node and a simple form using AJAX involved two key files. The first file is an HTML document containing a textbox and a button. The second file is the Node server responsible for handling requests. The goal w ...

iron-ajax attempting to send a multiline string or array subexpression using XHR

I'm facing a challenge with sending a multiline string from a paper-textarea element to the server. Initially, I tried sending it as is, but the newline characters were getting removed by iron-ajax due to possible JSON encoding problems. For my next ...

What is the best way to refresh a Windows 7 command prompt screen before executing a new function in Node.js?

I attempted system calls for cls and also tested out this code snippet: function clear() { process.stdout.write('\u001B[2J\u001B[0;0f'); } Unfortunately, none of the options seem to be effective. ...

Manage Datatables: Efficiently toggling the display of multiple rows in a loop

This specific inquiry pertains to the Datatables plug-in for JQuery. I am working with an HTML table that contains entries in 3 languages: en, ru, fr. When a language is selected, the entries in the other two languages should be hidden. For instance, if E ...

javascript function to divide text into separate elements

Currently, I am facing an issue with my front end where a string of words (item names) fetched from the database is being displayed in a loop without any separation. The output appears as: Item name1Item name2 This problem arises due to passing the value ...

Is it possible to retain various delimiters after dividing a String?

In the code below, the someString gets split into an array using specified delimiters in separators var separators = ['\\.', '\\(', '\\)', ':', '\\?', '!&apos ...

Experiencing difficulties retrieving a response from an API call within the Express.js backend

My backend server built with express.js is having issues making an API call. When I attempt to visit http://localhost:3004/api/weather?city=[cityName], the expected json response from openweathermap.org is not received. Instead, my middleware displays a me ...

What methods can I use to distinguish between the use of a hardware keyboard and a soft keyboard on a hybrid tablet

Issue Description: I manage a small group of about 90 users who are crucial to our business. When one or two users from this group request changes to the user interface (UI) of their web app, we allocate development resources to meet their needs. However, ...

Steps to displaying the result

new Vue({ data: { folders : [{ name : 'folder1', isActive : 1, }, { name : 'folder2', isActive : 0, }, ] } } }) Is there a way to access the active val ...