1

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.

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?

6
  • You need an array of object's isn't it... then your structure above is wrong Commented Mar 15, 2016 at 4:06
  • what is the structure of the value returned by the api Commented Mar 15, 2016 at 4:07
  • there is no track info in the data? Commented Mar 15, 2016 at 4:09
  • @ArunPJohny updated my question. Added link. Commented Mar 15, 2016 at 4:11
  • what about the track value? Commented Mar 15, 2016 at 4:12

1 Answer 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

$.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>

Sign up to request clarification or add additional context in comments.

6 Comments

wow I didn't know can use map. You can use map whenever you want? I think it very depends on how the response structure look like right? Can you do a version of non-map? I want to learn how to put arrays to an object in this case. Thanks.
@Jennifer you are putting objects to an array... items is an array of object, we are using the Array.map() function to convert each item in the map to a different format and return a new array of those objects
array of objects mean? and is there anything called object array? I'm confused. Like {name:['abc','def']} is object of array or array of object?
{} is used for object notation and [] is for array... so the above one is an object which as a property called name whose value is an array. An array of objects will be [{name: 'x'}, {name: 'y'}, {name: 'z'}]
@Jennifer there is nothing calling object of arrays... object is singular... an object can have arrays as its property value
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.