Javascript 将数据推送到 json 对象中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28254515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:29:39  来源:igfitidea点击:

Push data into a json object

javascriptjqueryjson

提问by Anton D.

I'm making a chrome app and I want to save the name and the artist of a song in a json file. I know how it could work, but I don't know how to put in the data (here: name and artist) into a json array. so the var is:

我正在制作一个 chrome 应用程序,我想将歌曲的名称和艺术家保存在一个 json 文件中。我知道它是如何工作的,但我不知道如何将数据(此处:姓名和艺术家)放入 json 数组中。所以 var 是:

var favorites = [];

so if someone clicks the star the artist and the name of the song should be putted 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);
});

I hope someone can help me :)
Sorry for my bad english

我希望有人可以帮助我 :)
抱歉我的英语不好

回答by Sudhir Bastakoti

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

回答by sandman

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