1

I'm trying to create a dataset from an API backend I've set up in my project. 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.

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.

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: enter image description here

1
  • 2
    May you also post what you actually get from estimateData? Commented Jan 8, 2020 at 14:37

3 Answers 3

2

I'm not sure of what you mean by "checking the length". Here is an example of your desired console.log output

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.

Good luck

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the Object.entries and map method suggestions. Your code worked perfectly.
1

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:

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

Comments

1

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]

You then iterate this array to construct this output object :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.