I'm trying to create an array of 120 objects (hex's for a map) and then add info to each one.
When I use map the id is supposed to be the index of the current object and I can console log the correct, current index as expected but for some reason EVERY object has an id of 119. I've looked at some of the other map examples on here and with Mozilla and I'm not understanding where I'm going wrong.
export class MapComponent implements OnInit {
arrayOfObjects = Array(120).fill({})
hexTiles = this.arrayOfObjects.map( (hex, index) => this.createHex(hex, index))
constructor() { }
ngOnInit() {
}
createHex(hex, index){
console.log('Current Index', index)
hex['id'] = index
hex['x-coordinate'] = null
hex['y-coordinate'] = null
hex['mapped'] = false
hex['terrain'] = ''
hex['details'] = ''
return hex
}
}
UPDATE I have tried a suggested solution but am now getting an array of 120 empty objects. Here is the updated code:
HTML: This displays nothing.
<div>
<div *ngFor="let hex of hexTiles; let i = index">
<pre>
{{hex}}
</pre>
</div>
</div>
TS: This will console log "Hexs (120) [empty × 120]"
export class MapComponent implements OnInit {
hexTiles = [...Array(120)].map((_, i) => this.createHex({}, i));
constructor() { }
ngOnInit() {
console.log('Hexs', this.hexTiles);
}
createHex(hex, index) {
hex['id'] = index;
hex['x-coordinate'] = null;
hex['y-coordinate'] = null;
hex['mapped'] = false;
hex['terrain'] = '';
hex['details'] = '';
return hex;
}
}
this.arrayOfObjects.map( (hex, index) => this.createHex(hex, index))to justthis.arrayOfObjects.map(this.createHex), not sure if this will fix your plroblem.