Search code examples
typescriptlinqgroup-bylinq.js

GroupBy with LinqTS(Typescript)


I am using LINQTS to have some information from via grouping some data.

 const registered_users_data = listData
  .groupBy(
    b => moment(b.created_at).format('YYYY/MM')
  )
  .select(x => {
    x.key, x.value.count();
  })
  .toArray();

For above code I am getting below response highlighted in red area

enter image description here

If I change the code to below

listData
  .groupBy(b => moment(b.created_at).format('YYYY/MM'))
  .select(x => x.value.count())
  .toArray();

then I get below result

enter image description here

I want to have both key and value count in response. Can anybody suggest what I am doing wrong in above code where I am getting null in array.


Solution

  • The curly brackets in x => { x.key, x.value.count(); } doesn't create an object when used in an arrow function because they are used to create a sequence of statements which should end with a return (if no return is provided, the value will be null, as in your case). What you can do is wrap the object in parantheses. See the MDN documentation

    So this is what the code should look like:

    const registered_users_data = listData
      .groupBy(
        b => moment(b.created_at).format('YYYY/MM')
      )
      .select(x => ({
        key: x.key,
        value: x.value.count();
      }))
      .toArray();