【问题标题】:How to get the attribute of JSON object in javascript containing the '#' in the key [duplicate]如何在键中包含'#'的javascript中获取JSON对象的属性[重复]
【发布时间】:2014-01-31 13:46:08
【问题描述】:

我有 last.fm 的 api 返回的 JSON 对象如下:

{
    "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"
        }
    }
}

现在我正在尝试从对象中获取图像,但图像 url 的键是 "#text"。我不知道这个值是如何在 Javascript 中提取的。我正在使用 AngularJS,但任何使用纯 JavaScript 的建议也是 okei。有什么方法可以在对象的键中使用“#”来获取它的值。

任何帮助将不胜感激。

干杯:)

【问题讨论】:

标签: javascript json angularjs last.fm


【解决方案1】:

foo['artists']['artist']['image'][0]['#text']

【讨论】:

    【解决方案2】:

    假设它在 obj 变量中,这将返回一个包含图像的数组

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

    ES6:

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

    就是这样。

    如果你想经典地遍历这个数组,用这个:

    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);   //Outputs the img url
    }
    

    干杯

    【讨论】:

    • 完美@edgar。非常感谢:)
    • 很高兴它帮助了你!干杯,来自玻利维亚拉巴斯
    猜你喜欢
    • 2018-02-05
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    • 2020-01-30
    • 1970-01-01
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多