要并排合并两个数组,我按照以下过程进行操作,但我得到了
这是我的代码
acs = [
{
"account": "Cash In Hand",
"liabilities": 0,
"assets": 8031597
},
{
"account": "Tax Acs",
"liabilities": 988363.72,
"assets": 0.98
},
{
"account": "Sundry Debtor",
"liabilities": 0,
"assets": 551
},
{
"account": "Sundry Creditor",
"liabilities": 0,
"assets": 0
}
];
acd: any;
acc: any;
newacc: any;
constructor() { }
ngOnInit() {
this.acd = this.acs.filter(f => f.liabilities !== 0);
this.acc = this.acs.filter(f => f.assets !== 0);
const bigger = this.acd.length > this.acc.length ? this.acd.length : this.acc.length;
this.newacc = [];
for (let i = 0; i < bigger; i++) {
if (this.acd.length > i) {
this.newacc[i].account = this.acd[i].account;
this.newacc[i].liabilities = this.acd[i].liabilities;
}
if (this.acc.length > i) {
this.newacc[i].accounts = this.acc[i].account;
this.newacc[i].assets = this.acc[i].assets;
}
}
}
如果我这样添加
this.newacc = [{}];
,第二个if
也会收到相同的错误,即this.newacc[i].accounts
我在这里犯了什么错?还是有最简单的方法将两个数组并排组合?这两个数组的长度无关,并且不进行任何连接。
最佳答案
您应该使用push
方法。问题是您要使用C++
语法添加元素。
this.newacc[i].account = this.acd[i].account;
如前所述,可以通过传递所需对象作为参数来使用
push
方法。newacc.push({account:acd[i].account, liabilities : acd[i].liabilities });
acs = [ { "account": "Cash In Hand", "liabilities": 0, "assets": 8031597 }, { "account": "Tax Acs", "liabilities": 988363.72, "assets": 0.98 }, { "account": "Sundry Debtor", "liabilities": 0, "assets": 551 }, { "account": "Sundry Creditor", "liabilities": 0, "assets": 0 } ];
acd = acs.filter(f => f.liabilities !== 0);
acc = acs.filter(f => f.assets !== 0);
const bigger = acd.length > acc.length ? acd.length : acc.length, newacc = [];
for (let i = 0; i < bigger; i++) {
if (acd.length > i)
newacc.push({account:acd[i].account, liabilities : acd[i].liabilities });
if (acc.length > i)
newacc.push({account:acc[i].account, assets : acc[i].assets });
}
console.log(newacc);