What is the best way to incorporate additional data into a TypeScript object that is structured as JSON?

I'm exploring ways to add more elements to an object, but I'm uncertain about the process.

My attempts to push data into the object have been unsuccessful.

people = [{
  name: 'robert',
  year: 1993
}];

//I aim to achieve this

people = {
  name: 'joe',
  year: 1992
}

//I want it to function as follows

people = [{
  name: 'robert',
  year: 1993
}, {
  name: 'joe',
  year: 1992
}];

I desire the capability to access it using people[0].name

Answer №1

To make the people variable an array of objects, you can do the following:

const people = [{ name: 'Alice', age: 30 }];

If you want to include a new object in the people array, you can use this code snippet:

const newPerson = { name: 'Bob', age: 25 };
people.push(newPerson);

To access specific objects or properties within the array, you can use these lines of code:

people[0];
people[0]['name'];

If you encounter any issues later on, it might be helpful to define the type for the people array as shown below:

export class AppComponent {
  // your properties and methods
}

interface Person {
  name: string;
  year: number; 
}

You can then declare your variables with the specified typings directly in your main code:

const people: Person[] = [{ name: 'Alice', age: 30 }];
const newPerson: Person = { name: 'Bob', age: 25 };
people.push(newPerson);

Answer №2

Give this a shot

people.push({ name: 'joe', year: 1992 });

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

Transforming dates from JSON and showcasing them on a DataTable

I'm facing an issue with my local JSON file where the dates are being rendered in a DataTable as /Date(1350028800000)/ (10/12/2012). I came across this thread which talks about converting the date format, but I need help figuring out how to implement ...

What are the steps to convert this code into Angular syntax?

After realizing that using jQuery alongside Angular is not a good practice, I am determined to modify my code in this Angular App to eliminate the need for jQuery. Currently, I have a page that displays menu items fetched from the server and I loop throug ...

Typescript | The extension of formikProps on IProps in Typescript is lacking 27 Props

I'm currently working with Formik in TypeScript and I'm trying to integrate a simple form component into TS within another component where I extract the defaultValues and validationSchemas. The challenge lies in accessing only the necessary form ...

Utilize designated columns to create a new column by associating it with JSON data

Currently, I am working with a data frame that contains the following information: A B C 1 3 6 My objective is to extract columns A and C and combine them to create column D, which should look like {"A":"1", "C":"6}. Th ...

The value for $routeParams.param appears to be undefined

I have set up a route and am attempting to send parameters to a controller: app.js .config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('spot', { url: "/spot/:param", templateUrl: "templates/spot.html", ...

Struggling with TypeScript errors when using Vue in combination with Parcel?

While running a demo using vue + TypeScript with Parcel, I encountered an error in the browser after successfully bootstrapping: vue.runtime.esm.js:7878 Uncaught TypeError: Cannot read property 'split' of undefined at Object.exports.install ...

Components in Angular 5 app hosted on Firebase fail to load

I successfully deployed my Angular 5 app to Firebase using the commands firebase init and firebase deploy. By default, the main page is pulled from the index.html file within the public directory. To ensure that my index.html was displayed, I made a chan ...

Unable to find custom components when using react-router

My goal is to improve the organization of my Routes in React and separate concerns. I am currently utilizing react-router-dom version 5. Within my Application Routes component, I have structured it with 3 children components: AuthenticatedRoutes PublicRo ...

Error: The variable "weather" is not defined while using React with the weatherbit API

I'm currently developing a React application that utilizes the Weatherbit API. However, I have encountered an issue with the weather object when calling my data array. Below is the code snippet where the problem occurs: import React from "react&q ...

How to overcome Django's QueryDict List limitations

Is there a way to send data from a webpage to a django view for serialization into JSON without using QueryDict? I prefer to use simplejson to read the request, flatten it, and save the data to the database. How can I format the data so that simplejson can ...

The total sum of values within labels that share the same class

I am attempting to sum up all the values of class tmpcpa and store the result in final_cpa, but for some reason final_cpa always ends up being 0. document.getElementById('cpa' + arr[0]).innerHTML = cpa + '(' + '<label id="tmp ...

Tips for maintaining JSON data in CK Editor

I'm having an issue where my JSON data is not being displayed in CKEditor when using this code function retrieveRules(){ $.ajax({ url: "api", type: "POST", data: { version:'0.1' }, ...

Synchronize data with Microsoft AJAX using force sync

When working with the Microsoft AJAX framework, I encounter a problem where my AJAX calls are asynchronous when I actually need them to be synchronous. I'm struggling to find a solution for this issue. In addition, I have been having difficulty findi ...

A guide on showcasing JSON format in a table view interface

Recently, I have ventured into the world of IOS development and I am faced with a task to showcase JSON fetched data in a UITableView. The JSON structure that I am working with looks something like this: {"output":[{"id":{"php":"1"},"name":{"php":"ramkuma ...

Intellisense from @reduxjs/toolkit is not showing up in my VS Code editor

My experience with vscode is that intellisense does not recognize @reduxjs/toolkit, even though the code itself is functioning correctly. I have already installed the ES7+ React/Redux/React-Native snippets extension from here. Here are a couple of issues ...

Automatically update Dropdown options with value and text through an ajax json request

I am working on dynamically populating a dropdown list with text and values fetched using an ajax call to retrieve a JSONObject. While my current code successfully populates the dropdown, I need the value to be different from the text as I intend to store ...

A guide on utilizing JTA for sending an array of objects through Jax-RS using POST requests

One of my challenges involves a jax-rs REST service that sends POST requests containing an ArrayList<Book> objects to the server. Upon receiving these requests, the server must iterate through each Book item, convert it into a BookEntity using JPA ...

Caution: It is essential for each child within a list to possess a distinct "key" property - React Native issue alert

Hello everyone, I am currently working on building a list in an app using react-native. I have been following a tutorial video and my code is identical to the instructor's, but I keep encountering an error that says each child in the list needs a key ...

Enter information to accompany your images in the description box

After browsing through numerous websites tonight, I stumbled upon this code. My goal is to create a photo upload page on Google Drive and set up a dropbox for it. I'm facing an issue where the information inputted into my placeholder box (city and ye ...

Verify if an item is present within a separate array

To determine if an object in one array exists in another array, we can use the combination.some() method with a condition that checks for a match based on specific criteria. In the example below, the event array returns true while the event1 array return ...