简体   繁体   中英

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

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

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

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 ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM