简体   繁体   中英

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

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);
}

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);

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 .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM