-2

I have an array of object. Array length is 12. I need to add months to each object, whats the best way to add months

  array = [ {name:"aa"},{name:"bb"}, {name:"cc"}.......]. 

Result I want

array = [ {monthName: 'January', name:"aa"},{monthName: 'February',name:"bb"}, {monthName: 'March',name:"cc"}............]. 
developer
  • 301
  • 3
  • 14

5 Answers5

1

Since the month names are immutable and you already know the array is exactly length 12, simply do it manually, one by one. There are fancier ways to do it but none are as easy to understand or as efficient with resources.

array[0].monthName = 'January';
array[1].monthName = 'February';
array[2].monthName = 'March';
...
Benjamin
  • 1,372
  • 2
  • 12
  • 20
1

store all the months in an array months = ['January', 'February', 'March'.....]

loop through your array and match indexes

array.map((x, index) => {
  if(months[index]) {
    x.monthName = months[index];
  }
  return x;
}
rbansal
  • 108
  • 2
  • 12
1

You can add an array of months and without mutating the array you can create another variable based on your first array and add the month as prop:

let array = [{
  name: "aa"
}, {
  name: "bb"
}, {
  name: "cc"
}];

let months = ["JAN", "FEB", "MAR"]
const res = array.map((el, index) => ({
  name: el.name,
  month: months[index]
}));



console.log(res)
Aziz.G
  • 3,599
  • 2
  • 17
  • 35
1

First, you have to declare array which will have month as below array

let month = ['January',February', .... ];

Now you have to iterate source array i.e array and push month property for each object. Code snippets provided below.

array.forEach(element,index)=>{
     element['monthName'] = month[index]
}
Ramin eghbalian
  • 2,348
  • 1
  • 16
  • 36
Dutt Patel
  • 11
  • 2
0

Define an array of months yourself or get it from a library like moment.js.

This way you are ready to work with dates later if you need much easier. You also get localization (no easy task) and short names if you prefer (e.g. 'Jan' instead of 'January').

var array  = [{name:"aa"}, {name:"bb"}, {name:"cc"}];
var months = moment.months(); // or .monthsShort();

array.forEach((e, idx) => {
   if (months[idx]) e.monthName = months[idx];
});

console.log(array);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>

Here is the documentation on months() and monthsShort().

vicpermir
  • 3,544
  • 3
  • 22
  • 34