简体   繁体   English

带有数组的 Angular Javascript 对象,循环遍历并获取每个数组的长度?

[英]Angular Javascript object with arrays, looping through and getting length of each array?

I'm trying to create a dataset from an API backend I've set up in my project.我正在尝试从我在项目中设置的 API 后端创建数据集。 I've already managed to group my api call on the date but now I need to check the length of each date array that is created by lodash.我已经设法在日期上对我的 api 调用进行分组,但现在我需要检查由 lodash 创建的每个日期数组的长度。

How would I do this because every attempt I've tried so far has failed.我该怎么做,因为到目前为止我尝试过的每一次尝试都失败了。 The image I've included shows the console.log after I have grouped my result, it also shows the amount of entries in each array which is exactly what I want to retrieve.我包含的图像显示了对结果进行分组后的 console.log,它还显示了每个数组中的条目数量,这正是我想要检索的内容。

Current code, I removed my attempt at solving this problem because I would only get back undefined results.当前代码,我取消了解决此问题的尝试,因为我只会得到未定义的结果。

        ngOnInit() {
        this._estimateService.getEstimates()
            .subscribe(estimateData => {
                const groupedEstimateData = groupBy(estimateData, 'estimate_date');
                console.log(groupedEstimateData);
            });
        }

Example of desired result:所需结果示例:

2019-12-09, 47
2019-12-10, 6
etc

Image:图片: 在此处输入图片说明

I'm not sure of what you mean by "checking the length".我不确定“检查长度”是什么意思。 Here is an example of your desired console.log output这是您所需的 console.log 输出的示例

ngOnInit() {
        this._estimateService.getEstimates()
            .subscribe(estimateData => {
                const groupedEstimateData = groupBy(estimateData, 'estimate_date');
                Object.entries(groupedEstimatesData).map(([date, estimatedData]) => {
                    // do what you want there with each line
                    console.log(date, estimatedData.length);
                });
            });
        }

You can have a look at Object.entries and map methods.您可以查看Object.entriesmap方法。

Good luck祝你好运

You could do something like:你可以这样做:

const groupsWithCounts = Object.keys(groupedEstimateData).map(key => {
    [key]: groupedEstimateData[key],
    total: groupedEstimateData[key].length
})

Now groupsWithCounts will be an array of objects with this structure:现在groupsWithCounts将是一个具有以下结构的对象数组:

{
    2019-12-9: [item, item, item, ...], // the original items
    total: 47 // the total count of items
}

You can do this simply with :您可以简单地使用:

 const dates = Object.keys(groupedEstimateData); let output = {}; dates.forEach( date => output[date] = groupedEstimateData[date].length );

Object.keys(groupedEstimateData) will give you an array ["2019-12-09", "2019-12-10", etc] Object.keys(groupedEstimateData)会给你一个数组["2019-12-09", "2019-12-10", etc]

You then iterate this array to construct this output object :然后迭代这个数组来构造这个输出对象:

{
    "2019-12-09" : 47,
    "2019-12-10" : 6,
    etc
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM