Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push data into JSON array

I'm making a Chrome app and I want to save the name and the artist of a song into a json file. I know how that can be done, but I don't know how to put in the data (here: title and artist) into a json array. We assign:

var favorites = [];

So if someone presses the star, the artist and the name of the song should be put into favorites:

$(document).on('click','.fa-star-o', function() {
    var title = $(this).parent().find('.tracktitle').text(),
        artist = $(this).parent().find('.artist').text();

    $(this)
        .removeClass('fa-star-o')
        .addClass('fa-star');
    $('<li/>')
        .append('<span class="tracktitle">'+ title +'</span>')
        .append('<span class="artist">'+ artist +'</span>')
        .prependTo($favorites);
});
like image 656
Anton D. Avatar asked Jan 31 '15 17:01

Anton D.


2 Answers

you could use .push() to add object to your array, as:

//create object
var myObj = {
    "artist" : artist,    //your artist variable
    "song_name" : title   //your title variable
};
//push the object to your array
favorites.push( myObj );
like image 157
Sudhir Bastakoti Avatar answered Oct 17 '22 20:10

Sudhir Bastakoti


I don't know about the favorite format. But if it's a JSON string you want, you can use JSON.stringify() to construct it.

myJString = JSON.stringify({artist: artist, title : title});
like image 44
sandman Avatar answered Oct 17 '22 20:10

sandman