Replacing objects in a 2D array by passing reference copies

I have an array of 2D objects used for creating a clickable HTML editor (Tile editor). Each object in the array contains information about which image to display.

interface Tile {
   id: number,
   image: string,
   category?: number
   skin?: string
   schema?: string
}


tileEditor = 
 [ row: {Tile, Tile, Tile, Tile},
   row: {Tile, Tile, Tile, Tile},
   row: {Tile, Tile, Tile, Tile} ]

This is how it looks like in HTML:

 <table>
    <tr *ngFor="let rows of tileEditor">
      <td *ngFor="let cell of rows.row" (mousedown)="canvasDown(cell)">
       <img src="{{ cell.image }}" />
      </td>
    </tr>
  </table>

The goal is to replace an empty Tile object with the selected Tile object upon clicking. However, updating each property individually can be cumbersome, as demonstrated in the canvasDown(tile: Tile) function.

In essence, I wish to achieve this functionality in canvasDown(tile: Tile):

 canvasDown(tile: Tile) {
     tile = this.selectedTile
  }

Is there a way to accomplish this without just updating the reference copy?

Any insights or suggestions would be greatly appreciated. Thank you!

Answer №1

If you want to generate this specific type of data

getTileObjectInit(){
   return {
   id: '',
   image: '',
   category: '',
   skin: '',
   schema: ''
 }
}

tileEditor = 
 [ {row: [this.getTileObjectInit(), this.getTileObjectInit(), this.getTileObjectInit(), this.getTileObjectInit()]},
   {row: [this.getTileObjectInit(), this.getTileObjectInit(), this.getTileObjectInit(), this.getTileObjectInit()]},
   {row: [this.getTileObjectInit(), this.getTileObjectInit(), this.getTileObjectInit(), this.getTileObjectInit()]} ]

How can you Transform an Object into an array ?

this.tileEditor.forEach(e => e.row = Object.values(e.row));
//Object.values() will give you an array of values from the object, without including their keys.

Another approach to Convert your Object into an array

this.tileEditor.forEach(e => e.row = Object.keys(e.row).map(key => e.row[key]));
// Using Object.keys() will provide an array of keys of the object,
// then .map() function maps the data using the key of the object

Now, your tileEditor.row object has been converted into an array. You can now utilize it in a *ngFor loop

Once you have structured your data like this, you can display the images in HTML with the following code snippet

<table>
    <tr *ngFor="let rows of tileEditor">
      <td *ngFor="let cell of rows.row" (mousedown)="canvasDown(cell)">
       <img src="{{ cell.image }}" />
      </td>
    </tr>
</table>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a convenient HTML parser that is compatible with Nativescript?

I have tested various libraries like Jquery, Parse5, and JsDom, but unfortunately they are not compatible with nativescript. Jquery relies on the DOM, while Parse5 and JsDom require Node.js which is currently not supported by nativescript. I am in need of ...

Unable to resolve all dependencies for UserService: (Http, ?)

After transitioning to the latest Angular2 version 2.0.0-beta.17, my project started experiencing issues. The structure of my UserService is as follows: import { Injectable} from '@angular/core'; import { Http } from '@angular/http'; ...

Exploring the wonders of arrays and functions in C++

I have created a program that takes two inputs from the user and uses an array inside a loop to pass them to a function within a class, which then displays the two numbers. The issue arises when the user inputs the number 1. The program continues to promp ...

JavaScript throws a "null is null or not an object" error when attempting to

I am dealing with a div that contains flash content in the form of Open Flash Chart. However, I encounter a javascript error when trying to remove child divs using $("#mydiv").children().remove() specifically in IE 8: The error message reads: "null is n ...

What causes the circular progress bar to disappear when hovering over the MUI React table?

My goal was to create a table with a CircularProgressBar that changes its background color from orange to dark blue when hovering over the row. However, despite my efforts, I couldn't get it to work as intended. Additionally, I wanted the progressBar ...

The object returned by bodyParser is not a string but a data structure

I have been working on implementing a JSON content listener in Typescript using Express and Body-parser. Everything is functioning perfectly, except when I receive the JSON webhook, it is logged as an object instead of a string. import express from 'e ...

When attempting to connect to the MongoDB cloud, an unexpected error arises that was not present in previous attempts

npm start > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="650800170b4816001713001725544b554b55">[email protected]</a> start > nodemon index.js [nodemon] 3.0.2 [nodemon] to restart at any time, enter ...

What does the error "Cannot access property 'length' of null when using 'angular'" mean?

I am currently working on counting the initial li items and encountering an issue with 'Cannot read property 'length' of null' after fetching data from the server using a unit test case. Here is my code: import { ComponentFixture, Tes ...

Discover a magical feature in Angular with the Observable Array and its *ng

I'm encountering an issue that says "ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays." My goal is to establish a Basket store in order ...

Converting an array of objects into a flat array of objects with Javascript

My data array requires conversion to a flattened array returning new header and data. For instance, the first object contains a name with three data points: "title, first, last." The desired output is: From : { gender: 'male', name: { ...

Is there a way to create a mask that only permits phone numbers to be entered

How can Angular 2 support model-driven forms and enable the implementation of a directive for masking an input field, such as formatting phone numbers like (123) 123-4567? ...

Unable to adjust image opacity using jQuery

I am attempting to change the opacity of an image based on a boolean flag. The image should have reduced opacity when the var pauseDisabled = true, and return to full opacity when pauseDisabled = false. To demonstrate this, I have created a fiddle below. ...

The forwarded reference of the material-ui component is consistently empty

Currently, I am exploring the creation of a navbar with a drawer element using the material-ui library. I am attempting to pass the <Drawer> Component to the parent navbar so that I can access the toggleDrawer function within my NavDrawer component. ...

Disabling modal popup buttons in Bootstrap 4 using Javascript

JSFiddle DEMO: https://jsfiddle.net/2yx16k8L/ I'm encountering an issue with my JS code. I want a click on a div to open the entire content within it. However, this action is causing the modal button in the dropdown to stop working. How can I resolve ...

Error in Angular 13: Struggling to remove the likelihood of an object being null

I am working on a piece of code that includes the following: var item = document.getElementById("div0"); item.parentNode.removeChild(item); // The error seems to be here Every time I run this code, I encounter the error message: object is p ...

What causes a user to log out when the page is refreshed in a React/Redux application?

Each time the page is reloaded in my React/Redux application, the user gets logged out, even though I have stored the token in localStorage. There seems to be an error somewhere. The token should ideally be saved when the user logs in and not lost upon rel ...

Guide on scheduling MongoDB calls with Node.js recursively

Is there a way to trigger this code or function periodically? I am considering using setInterval, for example: setInterval('function()', 5000);. However, I am unsure about how to implement it in this specific scenario. list = []; MongoClient.conn ...

What is the best way to retrieve key/value pairs from a JSON object?

After making a call to an external service, I receive a domain object in return: var domainObject = responseObject.json(); This JSON object can then be easily accessed to retrieve specific properties. For example: var users = domainObject.Users The &ap ...

What could be causing the if statement to evaluate as false even though the div's style.display is set to 'block'?

Building a react application using createreactapp and encountering an issue with an if statement that checks the CSS display property of a div identified as step1: const step1 = document.getElementById("step-1") if (step1.style.display === 'blo ...

Leveraging recompose utility within the structure

I am exploring the use of recompose utility functions as a React element, enabling me to incorporate them into JSX as higher-order components (HOC). const enhancedInput = props => { return (<OnlyUpdateForKeys keys={['name']> ...