16

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);
});
1
  • 1
    JSON is a string, a sequence of characters, in a specific format. favorites is an Javascript Array. Those are very different things. Commented Jan 31, 2015 at 17:48

4 Answers 4

27

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 );
Sign up to request clarification or add additional context in comments.

Comments

3

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});

Comments

0
var myObj = {
    "artist" : $(this).parent().find('.artist').text();
    "song_name" : $(this).parent().find('.tracktitle').text()
};

$(document).on('click','.fa-star-o', function() {
    $(this).removeClass('fa-star-o').addClass('fa-star');
    favorites.push(myObj); //push the object to your array
});

Comments

0

I get this error

error TS2339: Property 'push' does not exist on type '{}'.

in code

let controls = {};

controls = {
    key1: new FormControl({ value: 'value1', disabled: true }),
    key2: new FormControl({ value: 'value2', disabled: true }),
    ...
}

let key3FormControl : new FormControl({ value: 'value3', disabled: true })

controls.push(key3FormControl); //error 'push' does not exist on type '{}'

I should not even use push, but simply add a new value in JSON Object as follows:

controls['key3'] = key3FormControl ;

Comments

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.