What is the best way to dynamically insert values into a JSON object?

I'm currently working with a JSON object in Angular and I need to dynamically add values that the user enters. Despite searching extensively, I haven't found a straightforward method to achieve this. I simply want to understand how to append key-value pairs to the JSON object.
Below is the TypeScript code sample:

 people: any[]=[{
          "name": "jacob",
          "age": 22 },
          {
          "name": "sruthi",
          "age": 29 }
      
  ]

My goal is to update the JSON object with new names and ages as users input them.
The corresponding HTML code snippet is shown below:

  <input type="text" class="frm-control" placeholder="Enter Name" (change)="insert_name($event.target.value)">  
  <input type="text" class="frm-control" placeholder="Enter Age" (change)="insert_age($event.target.value)">
  <br>
  <button type="button" class="btn btn-success" style="margin-top:10px;" (click)="submit()">Submit</button>

Answer №1

One way to achieve this is by using the push() function

this.people.push({name:this.name, age:this.age})

Answer №2

If you want the simplest way to achieve this, just use people.push(<person>). However, for a more Angular or general best practice approach, consider creating a Person class instead of using the any type.

 class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
 }
 
 const people = [];
 people.push(new Person('Jacob', 22));
 people.push(new Person('Sruthi', 29));


console.log(people);

When your Button is clicked, it will trigger a function that adds a new Person object to the people array.

To enhance your form functionalities including validation, submission, and modeling, I suggest implementing Reactive Forms.

https://angular.io/guide/reactive-forms

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

Error displaying messages from the console.log function within a TypeScript script

My node.js application runs smoothly with "npm run dev" and includes some typescript scripts/files. Nodemon is used to execute my code: This is an excerpt from my package.json file: { "scripts": { "start": "ts-node ./src/ind ...

What are the methods to alter validation for a Formfield based on the input from other Formfields?

My aim is to create a Form where input fields are required only if one or more of them are filled out. If none of the fields have been filled, then no field should be mandatory. I came across a suggestion on a website that recommended using "valueChanges" ...

Exploring JSON objects within a Flask application

@app.route('/parseJSON',methods=['GET','POST']) def parseJSON(): input_name = request.form["search"] url = "https://api.github.com/search/users?q={0}".format(input_name) loadurl = urllib.urlopen(url) data = jso ...

Using boolean value as default input value in React

When trying to set the default value of a controlled checkbox input from my request, I encountered an error stating "Type 'boolean' is not assignable to type 'string | number | readonly string[] | undefined'". Do you have any suggestion ...

What is the most effective way to determine the data type of a variable?

My search skills may have failed me in finding the answer to this question, so any guidance towards relevant documentation would be appreciated! I am currently working on enabling strict type checking in an existing TypeScript project. One issue I'v ...

Preserving the information from a webpage by utilizing casperjs for scraping and saving table data

What is the most efficient way to preserve table data collected during a web scraping process with casperjs? Saving it as a file after serializing into a json object. Sending an ajax request to php and then storing it in a mysql database. ...

Tips for managing boolean values in a JSON data structure

My JSON object is causing issues because it has True instead of true and False instead of false. How can I fix this problem? The code snippet below shows that obj2 is not working properly due to boolean values being capitalized. <!DOCTYPE html> < ...

Harnessing the power of React context alongside React hooks in TypeScript

Here is an example demonstrating my attempt at implementing react's context with react hooks. The goal is to easily access context from any child component using the code snippet below: const {authState, authActions} = useContext(AuthCtx); First, I ...

Node.js, sigma.js, and the typescript environment do not have a defined window

When attempting to set up a sigma.js project with node.js in TypeScript, I encountered a reference error after starting the node.js server: ts-node index.ts The problem seems to be located within the sigma\utils\index.js file. <nodejsproject& ...

"Configuration parameter stored in a JSON file within the public directory of a Create React App

My public folder contains a file called config.json, and I need to set different parameters for development and production modes. The file is fetched when my app loads using fetch('config.json').then(). Is there a way to structure my config.json ...

How to write JSON while maintaining double backslashes

I am looking for a way to save Python data structures as JSON in a Postgresql database. When using json.dumps(), the JSON format is correct, as shown below: >>> import json >>> j = { 'table': '"public"."client"' } &g ...

Sorting through a list of strings by checking for a specific character within each string

After spending years dabbling in VBA, I am now delving into Typescript. I currently have an array of binary strings Each string represents a binary number My goal is to filter the array and extract all strings that contain '1' at position X I ...

Ways to induce scrolling in an overflow-y container

Is there a way to create an offset scroll within a div that contains a list generated by ngFor? I attempted the following on the div with overflow-y: @ViewChild('list') listRef: ElementRef; Then, upon clicking, I tried implementing this with s ...

Javascript Google Maps API is not working properly when trying to load the Gmap via a Json

Trying to display a map using Gmaps and Jquery Ajax through JSON, but encountering difficulty in getting the map to appear on the page. The correct coordinates are being retrieved as confirmed by testing in the console. Puzzled by why it's not showin ...

Troubleshooting a Django TypeError while parsing JSON: A step-by-step guide

After running the code below, I am encountering a TypeError in the browser. The error specifically occurs at the final line with the message 'NoneType' object is not subscriptable (I am attempting to retrieve all the URLs for each item). What&apo ...

Issue encountered while attempting to transform a POJO Class into a JSON String using GSON

I've been attempting to convert a POJO class to Json using Gson, but I keep encountering an error for which I don't have a clear solution. My Java version is 19 and here is my class: public class PlayerModel { String player; UUID uuid; ...

Transforming a list into Json format within Robot Framework

Upon invoking a specific Get Regexp Matches function, I received the following list: ['{"result": 1, "error": { "namespace": "global", "reason": "unauthorized" } }'] While trying to verify values using the method below: Should Be Equal ${res ...

tips for dealing with nested json objects in C#

After sending a URL request and receiving a response in curl, I convert it into a JSON object that contains nested objects with numeric and dot values like 924.136028459. Here is an example: string arr1 = "{ "success":1, "results":[ ...

Here's how to retrieve a property from a union type object in Typescript without the need for type casting

I am facing a scenario with various types: export type a = { todo: string; }; export type b = { id: number; }; export type TodosAction = Action<string> & (a | b); In addition, I have a function defined as follows: function doSmth(action:To ...

The image hover feature is not functioning as expected in Angular 4

Currently, I am involved in a project using Angular 4. One particular section involves changing images on hover. Although I have implemented the following code, it does not seem to be functioning correctly for me. Interestingly, the same code works perfect ...