Javascript 如何将两个JSON对象组合成一个数组
我有两个JSON文件——一个是关于2015-16赛季英超联赛的数据,另一个是2016-17赛季的数据。每个文件中的JSON数据如下(仅提取): 等等。。。许多名称,在rounds数组中与此匹配 2016-2017年的数据与上述类似:Javascript 如何将两个JSON对象组合成一个数组,javascript,angular,typescript,Javascript,Angular,Typescript,我有两个JSON文件——一个是关于2015-16赛季英超联赛的数据,另一个是2016-17赛季的数据。每个文件中的JSON数据如下(仅提取): 等等。。。许多名称,在rounds数组中与此匹配 2016-2017年的数据与上述类似: { "name": "English Premier League 2016/17", "rounds": [ { "name": "Matchday 1", "matches": [ {
{
"name": "English Premier League 2016/17",
"rounds": [
{
"name": "Matchday 1",
"matches": [
{
"date": "2016-08-13",
"team1": {
"key": "hull",
"name": "Hull City",
"code": "HUL"
},
"team2": {
"key": "leicester",
"name": "Leicester City",
"code": "LEI"
},
"score1": 2,
"score2": 1
},
等等。。。许多名称,在rounds数组中与此匹配
这两个文件位于两个单独的json文件中。我正在Angular 2中开发一个应用程序,并使用了数据服务来获取这些数据。那部分很成功。然而,我需要使用ngFor来创建表中的行,为此,我要求这些数据像数组一样可编辑
我曾尝试将这两个json对象转换为数组,但未能成功
1我初始化了一个空数组,并尝试对每个对象执行array.push。那没用
arr=[];
if(this.data1516!=null && this.data1516!=undefined) {arr.push(this.data1516);}
if(this.data1617!=null && this.data1617!=undefined) {arr.push(this.data1617);}
2.我试过了。转让-
this.obj=Object.assign({},this.data1516,this.data1617)代码>
然后尝试将对象转换为数组,即使这样也不起作用
arr=[];
if(this.data1516!=null && this.data1516!=undefined) {arr.push(this.data1516);}
if(this.data1617!=null && this.data1617!=undefined) {arr.push(this.data1617);}
我希望最终的json单个文件是这两个对象的数组,如下所示:
[{obj1},{obj2}]在arr.push
这应该起作用:
arr=[];
if(this.data1516!=null && this.data1516!=undefined) {
arr.push(this.data1516);
}
if(this.data1617!=null && this.data1617!=undefined) {
arr.push(this.data1617);
}
或更短的版本(ES6)
代码中没有额外的]错误地更正了它
arr = [ ...this.data1516 , ...this.data1617 ];