Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add a property to reduce function

I have this code:

    source.map(data =>
      /*tslint:disable:no-string-literal*/
      Object['values'](
        data.reduce(
          (acc, { name, type, count }) => 
            (((acc[name] = acc[name] || { name })[type] = count), acc),
          {},
        ),
      ),
    ),

This code outputs this:

  {
    "name": "name1",
    "type": "type1",
    "size": 2,
    "total": 4
  },

I want to add one more property to the output so it looks like that:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  {
    "name": "name1",
    "type": "type1",
    "size": 2,
    "total": 4,
    "newProp": 'value'
  },

The new prop is a hardcoded prop so it wont come from the source..

What is the best way to do that?


After playing with a code turned out that I had to take the newProp value from the source.

source.map(data =>
      /*tslint:disable:no-string-literal*/
      Object['values'](
        data.reduce(
          (acc, { name, type, count, newProp }) => 
            (((acc[name] = acc[name] || { name })[type] = count), acc), //how would you assign a newProp value here? 
          {},
        ),
      ),
    ),

How would you assign a newProp value within a reduce funcion?

>Solution :

To add a new property to the output, you can use the spread operator (…) to copy the existing properties and then add the new property to the object. Here is an example of how this could be done:

source.map(data =>
  /*tslint:disable:no-string-literal*/
  Object['values'](
    data.reduce(
      (acc, { name, type, count }) => {
        const newProp = 'value';
        acc[name] = acc[name] || { name };
        acc[name][type] = count;
        acc[name] = { ...acc[name], newProp };
        return acc;
      },
      {},
    ),
  ),
),

To assign a newProp value from the source within the reduce function, you can use the same approach as above, but get the newProp value from the data object instead of setting it to a hardcoded value. Here is an example of how this could be done:

source.map(data =>
  /*tslint:disable:no
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading