Dynamically assigning values to class properties in Angular with Typescript is a powerful

I am working on a project where I have a class and a JSON object. My goal is to update the properties in the class based on the values in the JSON object, using Angular 9.

This is the class:

export class Searchdata{
  name:boolean=false;
  age:boolean=false;
  summer:boolean=false;
  winter:boolean=false;
  football:boolean=false;
  tennis:boolean=false;
}

And here is the JSON object:

[
   {
    "name": "name",
    "visible": true,
   },
   {
    "name": "age",
    "visible": true
   }, 
   {
    "name": "football",
    "visible": true
   }
]

The JSON object may not always have the same number of elements as the class has properties, but it can have all the same number of items for easier handling. I have explored various solutions, but for illustration purposes, below is how I envisioned the process working:

permPageData:any="The JsonObject";
tableSearchModel:Searchdata;

someFunction(){
  this.tableSearchModel = new Searchdata();

  permPageData.forEach(element => {
      if(element.name == this.tableSearchModel["element.name"])
        this.tableSearchModel[element.name] = element.visible;
  }
  return this.tableSearchModel;
}

Answer №1

I believe that when utilizing a class to define your model SearchData, it is best practice for the class to include methods related to the SearchData.

Consider this implementation:

.ts

class Searchdata{
  name = false;
  age = false;
  summer = false;
  winter = false;
  football = false;
  tennis = false;

  constructor() {}

  setFromJSON(obj: Array<{name:string,visible:boolean}>) {
    obj.forEach(element => {
      this[element.name] = element.visible;
    });
  }

  toString() {
    return `{name:${this.name},age:${this.age},summer:${this.summer},winter:${this.winter},football:${this.football},tennis:${this.tennis}}`;    
  }
}

const permPageData = [
  {
    "name": "name",
    "visible": true,
  },
  {
    "name": "age",
    "visible": true
  }, {
    "name": "football",
    "visible": true
  }
];

const tableSearchModel = new Searchdata();
console.log(tableSearchModel.toString());
tableSearchModel.setFromJSON(permPageData);
console.log(tableSearchModel.toString());

output

{name:false,age:false,summer:false,winter:false,football:false,tennis:false}
{name:true,age:true,summer:false,winter:false,football:true,tennis:false}

Although using an interface presents a different approach, I found it quite intriguing.

.ts

interface Searchdata{
  name: boolean;
  age: boolean;
  summer: boolean;
  winter: boolean;
  football: boolean;
  tennis: boolean;
}

function searchDataNew(): Searchdata {
  return {
    name: false,
    age: false,
    summer: false,
    winter: false,
    football: false,
    tennis: false
  };
}

function searchDataToString(sd: Searchdata) {
  return `{name:${sd.name},age:${sd.age},summer:${sd.summer},winter:${sd.winter},football:${sd.football},tennis:${sd.tennis}}`;    
}

function arrayDataToObjData(arr: Array<{name:string,visible:boolean}>): Searchdata {
  const obj: any = {};
  arr.forEach(element => {
    obj[element.name] = element.visible;
  });
  return obj;
}

const permPageData = [
  {
    "name": "name",
    "visible": true,
  },
  {
    "name": "age",
    "visible": true
  }, {
    "name": "football",
    "visible": true
  }
];

const tableSearchModel: Searchdata = {
  ...searchDataNew(),
  ...arrayDataToObjData(permPageData)
};
console.log(searchDataToString(tableSearchModel));

result

{name:true,age:true,summer:false,winter:false,football:true,tennis:false}

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

What is the best way to retrieve a value from a JSON object using AngularJS?

Using nodeJS, the server sends a JSON object to the controller: data = { "question": "theQuestion", "answer": "theAnswer" }; res.json(data); In the controller, I attempt to manipulate the variable as follows: data = QA.get(); $scope.q = data[que ...

Is the sudden disconnection from Chrome after a WebSocket handshake related to a domain mismatch or is it possibly a bug in Chrome?

I created my own WebSocket server using Python, but I encountered an issue where Chrome 4.0.249.78 dev (36714) always disconnects after the handshake process. Wanting to rule out any issues with my code, I tested it using the WebSocket server from , only t ...

Utilizing Javascript to implement a tooltip feature for dynamically inserted text

I recently incorporated a brief jQuery tooltip plugin into my site. It consists of approximately ten lines of code and works smoothly, as demonstrated in this demo. However, I encountered an issue when attempting to add new text that should also trigger t ...

Troubleshooting IE Freezing Issue Due to JavaScript Code with .addClass and .removeClass

Need some help troubleshooting why my code is causing IE to crash. After commenting out sections, I discovered that the issue arises when using .addClass and/or .removeClass inside the if conditions: if ( percentExpenses > 50 && percentExpenses ...

Tips on changing the date format in Typescript to the desired format

My date string reads as 2016-09-19T18:10:31+0100. Here's what I'm doing: let dateString:string = 2016-09-19T18:10:31+0100; let newDateString:Date = new Date(dateString); The output I'm currently getting is Tue Sep 19 2016 18:10:31 GMT+0530 ...

Display only the selected index and conceal the rest

I am facing an issue where I have added a label and input in ng-repeat. The functionality works fine when the user clicks edit to show the input and hide the label. However, the problem arises when the user clicks on the new button as it displays the new i ...

Error: The query has already been processed:

I'm encountering an issue while attempting to update the document. The error message indicates that the query has already been executed. MongooseError: Query was already executed: footballs.updateOne({ date: 'January 4' }, {}) app.post(& ...

JavaScript parameter not found

I am currently working on a block type plugin for Moodle and encountering some difficulties with my JS code. Due to my limited knowledge in JS and JSON, I am having trouble identifying the issue at hand. My code includes a function that adds a custom actio ...

Initiating the accordion feature requires two clicks and triggers an rotation of the icon

I managed to integrate some code I discovered for a FAQ accordion on my website. I am struggling with getting the title to expand with just 1 click instead of 2. Additionally, I would like the icon to rotate when expanding/collapsing, not just on hover. Be ...

Avoid having Masonry load all divs simultaneously

I have experience using jQuery Masonry on Tumblr, but now I want to incorporate it into my portfolio website for displaying my photography. However, I'm struggling to find a solution that allows sets of images to load in as the user scrolls to the bot ...

What is the best way to iterate through an array and dynamically output the values?

I am facing an issue with a function that retrieves values from an array, and I wish to dynamically return these values. const AvailableUserRoles = [ { label: 'Administrator', value: 1 }, { label: 'Count', value: ...

Encountering difficulties in retrieving the JSON data from the web service

My external web service contains JSON data which has been validated using the JSON Validator website. However, I am facing an issue where the success function in the code below is not running at all. The web service necessitates that the email and password ...

Respond to a recommendation with a response

I've been working on setting up a bot for my Discord server, and I recently added a "marry" command to it. Whenever a user makes an offer, a message announcing the proposal pops up with two reaction options. The first reaction signifies yes, while th ...

JavaScript problem with hovering action causing additional buttons to appear

Currently, I am developing a user interface where, upon hovering over an LI element, 2 buttons appear to provide additional functionality - "edit" and "remove". However, I am facing challenges with the mouse hit zones. The mouseover function works effect ...

Encountering an error when attempting to parse a JSON Object in Java from an AJAX call

** Latest Code Update ** My JavaScript and Ajax Implementation: $(function() { $("#create_obd").bind("click", function(event) { var soNumber = []; $('#sales_order_lineItems input[type=checkbox]:checked').eac ...

Javascript cards arranged in descending order

I'm in the process of developing a sorting feature that arranges cards in the DOM from Z to A with the click of a button. Although I've successfully implemented the logic for sorting the array, I'm facing difficulties in rendering it. Withi ...

Tips on how to obtain the element reference while using v-if in Vue

I need to conditionally display a div inside a card that slides within a carousel. My current approach is to check if the ancestor element contains the active class, and then use v-if to decide whether it should be rendered or not. However, this method d ...

Troubleshooting the Ineffective Replace Method in React Component

When working in my React component, I have implemented the use of the replace method to substitute a word. However, it seems that this functionality is not generating the expected outcome: const myComponent = () => { const [textVal, setTextVal] = ...

Defining variables within a jQuery function

Within my initialization function (init), I have defined some variables and an animation that utilizes those variables. The challenge arises when I want to use the same animation/variables in my clickSlide function. http://jsfiddle.net/lollero/4WfZa/ (Un ...

What causes a ReactJS component to disappear upon page refresh?

After the user clicks the Login button in the Instructor Login Form, I want to display the Instructor Profile component. Everything functions properly until I refresh the page, at which point the User Profile component disappears. Here is a screenshot of ...