Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add incremental counter in array inside an array

I have a array as follows


    data = [
    {
     sNo:1,
     month:[
     {
      id:1,
      value:0
     },
     {
      id:5,
      value:10
     }]
    },
     {
     sNo:2,
     month:[
     {
      id:6,
      value:10
     },
     {
      id:9,
      value:20
     }]
     }
    ]

I want to add an incremental counter in month array such that count keeps increasing till last element. So my final array looks like this

    data = [
    {
     sNo:1,
     month:[
     {
      id:1,
      value:0
      count:1
     },
     {
      id:5,
      value:10,
      count:2
     }]
    },
     {
     sNo:2,
     month:[
     {
      id:6,
      value:10,
      count:3
     },
     {
      id:9,
      value:20,
      count:4
     }]
     }
    ]

Here count is increasing regardless of element. How can I do that?

like image 573
Rosy Avatar asked Dec 05 '25 15:12

Rosy


1 Answers

you can :

  • define count outside the array treatment
  • and use array.map to add the new colum on each month

const data = [{
    sNo: 1,
    month: [{
        id: 1,
        value: 0
      },
      {
        id: 5,
        value: 10
      }
    ]
  },
  {
    sNo: 2,
    month: [{
        id: 6,
        value: 10
      },
      {
        id: 9,
        value: 20
      }
    ]
  }
];

let count = 0;
const result = data.map(one => ({ ...one,
  month: one.month.map(month => ({
    ...month,
    count: ++count
  }))
}));

console.log(result);
like image 72
jeremy-denis Avatar answered Dec 08 '25 05:12

jeremy-denis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!