简体   繁体   English

将数据推入 JSON 数组

[英]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.我正在制作一个 Chrome 应用程序,我想将歌曲的名称和艺术家保存到 json 文件中。 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.我知道如何做到这一点,但我不知道如何将数据(此处: titleartist )放入 json 数组中。 We assign:我们分配:

var favorites = [];

So if someone presses the star, the artist and the name of the song should be put into favorites :所以如果有人按了星标,艺术家和歌曲的名字应该被放入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:您可以使用.push()将对象添加到数组中,如下所示:

//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.但是如果它是你想要的 JSON 字符串,你可以使用 JSON.stringify() 来构造它。

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:我什至不应该使用推送,而只是在 JSON Object 中添加一个新值,如下所示:

controls['key3'] = key3FormControl ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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