0

Is there a way to write this out in a simpler and cleaner way in typescript

getMonthNames() {
this.months = [{ name: 'Jan', value: 0 }, { name: 'Feb', value: 1 }, { name: 'Mar', value: 2 }, { name: 'Apr', value: 3 }, { name: 'May', value: 4 }, { name: 'Jun', value: 5 },
{ name: 'Jul', value: 6 }, { name: 'Aug', value: 7 }, { name: 'Sep', value: 8 }, { name: 'Oct', value: 9 }, { name: 'Nov', value: 10 }, { name: 'Dec', value: 11 }];
this.toMonths = [{ name: 'Jan', value: 0 }, { name: 'Feb', value: 1 }, { name: 'Mar', value: 2 }, { name: 'Apr', value: 3 }, { name: 'May', value: 4 }, { name: 'Jun', value: 5 },
{ name: 'Jul', value: 6 }, { name: 'Aug', value: 7 }, { name: 'Sep', value: 8 }, { name: 'Oct', value: 9 }, { name: 'Nov', value: 10 }, { name: 'Dec', value: 11 }];

}

2
  • You can start with a random date in Jan, use a date formatting lib to get 3 char month, for loop for 12 iterations, populate the array with value as index+1, name as month name, accumulate in an array. Add one month at the end of each loop. Commented Jan 29, 2021 at 17:07
  • Maybe I need to be more clear I was wondering how can I assign that key-value pair to both objects without repeating it something like: this.month=this.tomonths=[{ name: 'Jan', value: 0 }, { name: 'Feb', value: 1 }, tc. Commented Jan 29, 2021 at 18:22

1 Answer 1

1

Based on your comment, it seems like you want to deep copy the object array. The simplest way to do this, would be to stringify followed by parsing, something like cloneDeep method from Lodash.

Here is what you should do, to avoid retyping:

this.months = [
  { name: 'Jan', value: 0 }, { name: 'Feb', value: 1 }, 
  { name: 'Mar', value: 2 }, { name: 'Apr', value: 3 }, 
  { name: 'May', value: 4 }, { name: 'Jun', value: 5 },
  { name: 'Jul', value: 6 }, { name: 'Aug', value: 7 }, 
  { name: 'Sep', value: 8 }, { name: 'Oct', value: 9 }, 
  { name: 'Nov', value: 10}, { name: 'Dec', value: 11}
];


// Deep copying here
this.toMonths = JSON.parse(JSON.stringify(this.months));

// false: because they refer to different objects
console.log(this.months[0] === this.toMonths[0])

// true: because the values within those objects are the same
console.log(this.months[0].value === this.toMonths[0].value)

Typescript Playground Link

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, that is precisely what I was trying to achieve
Hey @user2533398 , if this answer has helped you solve your problem, please consider accepting it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.