json - 尝试使用 Moment JS 循环对象
问题描述
我有一个部分从数组中提取数据并显示它并按月分组。为了让它显示日期对象,我必须从 JSON 文件中删除一个图层。
感觉就像我错过了一些非常小的东西,只需要做一个微小的改变来循环数据数组。谁能指出我做错了什么?
这是显示数据的表格:
<table class="table" *ngFor="let month of transactions | keyvalue">
<tr>
<th>{{month.key}}</th>
</tr>
<tr>
<td>
<table class="table" *ngFor="let customer of month.value">
<tr>
<td>
{{customer}}
</td>
</tr>
</table>
</td>
</tr>
</table>
这是对数据进行分组的组件:
export class AppComponent {
public transactions = {};
// Sample Data
customers = [
{
data: [
{
customer: {
name: "John"
},
// transaction_date: "2017-04-18"
transaction_date: "2019-9-22T13:56:11.971643+00:00"
},
{
customer: {
name: "Dick"
},
transaction_date: "2019-10-22T13:56:11.971643+00:00"
},
{
customer: {
name: "Harry"
},
transaction_date: "2019-7-22T13:56:11.971643+00:00"
},
{
customer: {
name: "John"
},
transaction_date: "2019-9-22T13:56:11.971643+00:00"
}
]
}
];
constructor() {}
ngOnInit() {
const monthName = item =>
moment(item.transaction_date, "YYYY-MM-DD").format("MMM");
// Establish groupBy array
this.transactions = _.chain(this.customers)
.groupBy(monthName)
.mapValues(items => _.map(items, "customer.name"))
.value();
const byMonth = _.chain(this.customers)
.groupBy(monthName)
.mapValues(items => _.map(items, "customer.name"))
.value();
console.log(byMonth);
return byMonth;
console.log(this.customers2);
}
}
如果我以不同的方式格式化 Json,它可以工作,但我也需要它与data []
数组一起工作。
// Working Array
customers2 = [
{
customer: {
name: "John"
},
// transaction_date: "2017-04-18"
transaction_date: "2019-9-22T13:56:11.971643+00:00"
},
{
customer: {
name: "Dick"
},
transaction_date: "2019-10-22T13:56:11.971643+00:00"
},
{
customer: {
name: "Harry"
},
transaction_date: "2019-7-22T13:56:11.971643+00:00"
},
{
customer: {
name: "John"
},
transaction_date: "2019-9-22T13:56:11.971643+00:00"
}
];
解决方案
尝试这个:
this.transactions = _.chain(this.customers[0].data)
const byMonth = _.chain(this.customers[0].data)
工作堆栈闪电战。
更新
您的customers
成员变量是一个只有一个元素的数组。
这就是添加[0]
访问它的原因。
您只需访问这样的数组中的第一个元素。数组名称和索引值(从零开始)。
再举几个例子:
customers = []; // <-- simple array
customers = [{}]; // <-- simple array with one object in it
如何访问它?
customers[0] // <-- first element
你的情况:
customers = [{ data: [] }]; // <-- simple array with one object in it with a property "data" which is another array.
如何访问它?
customers[0].data // <-- the solution
推荐阅读
- c# - 当 asp-page tag helper 的值不正确时,是否可能触发编译时错误?
- pandas - 在 pandas 的分钟级别添加具有其他日期时间列的列值
- java - 如何在 swagger-ui 上显示“/oauth/token”端点?
- codenameone - Display.getInstance().createSoftWeakRef(...) 用法
- java - PMD 因具有多个模块的项目的自定义规则集而失败
- python - 如何识别 HTML 的正确位以使用 python 抓取剧集数据
- flutter - 如何在flutter中本地保存int值
- python - 创建二进制数值数组表
- python - 用于键盘输入处理的 PyGame 单独线程
- reactjs - 绑定选择 react-hook-form