Home > Enterprise >  How can I push the same object to an array N times but be different objects in the array?
How can I push the same object to an array N times but be different objects in the array?

Time:06-02

I have this object below, where IMemberCard is an interface.

const memberCard: IMemberCard = { id: null, name: 'Member', rating: null, photoUrl: '/assets/images/user.png', type: null, eventCount: null, experienceLevel: null, years: null, certification: null, isPriority: null, memberStatus: null, receiveNotification: null};

Question - Is there a way to push() N of these objects into the array and make them different objects but with these values?

I know this works with a loop but aren't they the same object?

const memberCardArray: IMemberCard[] = [];
for (let i = 0; i < this.yogaband.members; i  ) {
   memberCardArray.push(memberCard);
}

CodePudding user response:

if it is always the same reference to memberCard, you can do this:

const memberCardArray: IMemberCard[] = [];
memberCardArray = Array.from({length: this.yogaband.members}).map(()=> memberCard);

CodePudding user response:

Depending on how your [all the objects] look and what the detailed requirements are, you could use one of these methods:

  • splice(start, deleteCount, item1, item2, itemN) if you have individual different items to add
  • fill(value, start, end) to add the same value multiple times to the array
  • concat(value0, value1, ... , valueN) to concatenate multiple arrays - the values here are arrays! Take care this method does not modify the original array where you call it from, but rather returns a new array.

Find a detailed reference on the MDN.

CodePudding user response:

You can use Array.prototype.fill():

const memberCard: IMemberCard = { id: null, name: 'Member', rating: null, photoUrl: '/assets/images/user.png', type: null, eventCount: null, experienceLevel: null, years: null, certification: null, isPriority: null, memberStatus: null, receiveNotification: null};

const getNMemberCards = (n, mc): IMemberCard[] => Array(n).fill({ ...mc })

const result: IMemberCard[] = IMemberCard(5, memberCard)

Code example:

const memberCard = { id: null, name: 'Member', rating: null, photoUrl: '/assets/images/user.png', type: null, eventCount: null, experienceLevel: null, years: null, certification: null, isPriority: null, memberStatus: null, receiveNotification: null};

const getNMemberCards = (n, mc) => Array(n).fill({ ...mc })

const result = getNMemberCards(5, memberCard)

console.log(result)

  • Related