我有来自服务器的paymentList json。我需要日期和时间。我正在使用moment.js。我正在创建一个新的属性paymentTime并在该属性中存储时间,但它没有更新。
this.paymentList.forEach(element => {
console.log(moment(element.paymentDate).format("hh:mm A"));
console.log(moment(element.paymentDate).format("DD-MMMM-YYYY"));
element.paymentTime = moment(element.paymentDate).format("hh:mm A");
element.paymentDate = moment(element.paymentDate).format("DD-MMMM-YYYY");
console.log(this.paymentList);
});
[
{
"paymentDate": "2018-01-09T09:21:13.759Z",
"loanAmount": "918553377499",
},
{
"paymentDate": "2017-12-27T09:30:41.276Z",
"loanAmount": "9880712423",
},
{
"paymentDate": "2017-12-27T07:49:09.892Z",
"loanAmount": "7259945267",
}
]
我知道如果我改变我的代码那么它会起作用,但我想要一种优雅的方式。
this.paymentList.forEach(element => {
var array = [];
var obj = {paymentTime: '', paymentDate: '', loanAmount: ''}
obj.paymentDate= moment(element.paymentDate).format("DD-MMMM-YYYY");
obj.paymentTime = moment(element.paymentDate).format("hh:mm A");
obj.loanAmount = element.loanAmount;
array.push(obj);
this.paymentList = array;
});
答案 0 :(得分:0)
你的第二个程序是好的方法,只需稍加修改即可。
let tempPaymentList:any = [];
this.paymentList.forEach(element => {
let obj = {paymentTime: '', paymentDate: '', loanAmount: ''}
obj.paymentDate= moment(element.paymentDate).format("DD-MMMM-YYYY");
obj.paymentTime = moment(element.paymentDate).format("hh:mm A");
obj.loanAmount = element.loanAmount;
tempPaymentList.push(obj);
});
this.paymentList = tempPaymentList;
console.log(this.paymentList)
实际上最好是获取主列表的副本,然后根据需要修改复制的列表。