Home > Net >  How to add a property to reduce function
How to add a property to reduce function

Time:12-07

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:

  {
    "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?

CodePudding user response:

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
  • Related