使用$ .each将值放入数组对象中

时间:2022-09-30 20:51:20

I want to produce something like this

我想生产这样的东西

album = {[
 name:'',
image:'',
tracks:[]
],[
 name:'',
image:'',
tracks:[]
]}

But now I'm stuck at appending the value into the right json object.

但现在我不得不将值附加到正确的json对象中。

var albums = {};

$.get("https://api.spotify.com/v1/artists/1rQX6kg84TqcwGtZHYIdn4/albums", function(data, status) {
  tempArr = [];
  $.each(data.items, function(i, obj) {

    tempArr.push(obj.images[0].url);
    albums['image'] = tempArr;
  });

  console.log(albums)

});

You can see the albumn data here http://jsfiddle.net/u5me8csx/1 Any help?

您可以在这里查看相册数据http://jsfiddle.net/u5me8csx/1任何帮助?

1 个解决方案

#1


1  

The syntax in the question for the albums object is wrong, you have swapped the brackets used for object and array notations.

相册对象的问题语法错误,您已交换用于对象和数组表示法的括号。

You can use Array.map() to iterate over the items and create the desired format like

您可以使用Array.map()迭代项目并创建所需的格式,如

$.get("https://api.spotify.com/v1/artists/1rQX6kg84TqcwGtZHYIdn4/albums", function(data, status) {
  var albums = data.items.map(function(item) {
    return {
      name: item.name,
      image: item.images[0],
      tracks: []
    }
  });
  console.log(albums);
  $('#result').text(JSON.stringify(albums, null, 2))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="result"></pre>

#1


1  

The syntax in the question for the albums object is wrong, you have swapped the brackets used for object and array notations.

相册对象的问题语法错误,您已交换用于对象和数组表示法的括号。

You can use Array.map() to iterate over the items and create the desired format like

您可以使用Array.map()迭代项目并创建所需的格式,如

$.get("https://api.spotify.com/v1/artists/1rQX6kg84TqcwGtZHYIdn4/albums", function(data, status) {
  var albums = data.items.map(function(item) {
    return {
      name: item.name,
      image: item.images[0],
      tracks: []
    }
  });
  console.log(albums);
  $('#result').text(JSON.stringify(albums, null, 2))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="result"></pre>