What is the method for inserting an object into a jsonArray in TypeScript?

I am trying to add an object to existing JSON data in TypeScript. I am new to TypeScript and have created an array variable called jsonArrayObject, which contains a boolean[] type. This jsonArrayObject holds a contactModel object with properties like fname, lname, id, and mobile. Below is the code snippet that I tried. Can someone please assist me?

let jsonArrayObject: boolean[] = [];

jsonArrayObject=[{
    contactModel:{
    fname:"vboyini",
    lname:"simha",
    id:"1",
    Mobile:"99768999"
    }
}];
var modelData :String={
 fname:"vboyini2",
lname:"simha2",
id:"2",
Mobile:"799768999"
}

Now, I want to prepend the array item (contactModel object) into the jsonArrayObject. I attempted the following code:

this.jsonArrayObject.unshift({"contactModel":any=modelData})

The above code is not working. Can someone please help me figure out how to achieve this? Thank you.

Answer №1

When adding an object to an array, there is no requirement to declare it as a boolean.

let jsonArrayObject = [];

jsonArrayObject.push({
  fname:"john",
  lname:"doe",
  id:"123",
  phone:"555-555-5555"
});

Answer №2

To begin with - you're approaching it the wrong way.

Define it in this manner:

    let jsonArrayObject = [];
    jsonArrayObject = [
        {
            fname: 'john',
            lname: 'smith',
            id: '1',
            Mobile: '123456789'
        }
    ];
    let modelData = {
        fname: 'jane',
        lname: 'doe',
        id: '2',
        Mobile: '987654321'
    }; 

After that, you can add modelData to the Array like this, or use other methods like unshift, slice, splice, etc.

jsonArrayObject.push(modelData);

Answer №3

There seems to be a compilation error in your scripts. The array values are mistakenly set as Boolean data type.

let jsonArrayObject: boolean[] = [];

You should correct the format by specifying the right data structure.

interface IContactModelData{
  fname:string;
  lname:string;
  id:string;
  Mobile:string;  
}

interface IContactModel{
  contactModel: IContactModelData   
}

let jsonArrayObject: IContactModel[] = [];

jsonArrayObject=[{
  contactModel:{
    fname:"vboyini",
    lname:"simha",
    id:"1",
    Mobile:"99768999"
  }
}];

var modelData:IContactModelData = {
  fname:"vboyini2",
  lname:"simha2",
  id:"2",
  Mobile:"799768999"
};

jsonArrayObject.push({contactModel:modelData});

Answer №4

When using the unshift method, there is no need to specify the type in the object.

Instead, you can simply use the following code:

this.jsonArrayObject.unshift({"contactModel":modelData});

In this code snippet, modelData represents a variable that is passed as an argument.

Answer №5

const userList = [];
const userObj={};
userObj={

    id:2,
    "name":"Jane Smith"
}
userList.push(userObj);

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

Using TypeScript and controllerAs with $rootScope

I am currently developing an application using Angular 1 and Typescript. Here is the code snippet for my Login Controller: module TheHub { /** * Controller for the login page. */ export class LoginController { static $inject = [ ...

Converting JSON to XML while preserving the original order of elements

Utilizing the following code snippet to translate JSON into XML across multiple XML files with varying JSON structures. String toXmlRequest = fullRequest.toString(); JSONObject jsonObj = new JSONObject(toXmlRequest); String X ...

I want to save the information for "KEY" and "textValue" in JSON format and then return it as a response when I make a request to app.get("/api"). How can I achieve this?

Working with GCP Document AI using Node.js and react.js, I have created a JSON structure (var jsonResult) in the provided code. In the for loop, I am extracting key and text value data by using console.log(key); and console.log(textValue);. However, my g ...

Upon closing the browser, the Angular ngx-cookie-service data disappears

Currently, I am working on setting a cookie using ngx-cookie-service so that I can retrieve it later as needed. Everything seems to be functioning properly as the code works well when refreshing the page, and the cookie is visible in Chrome developer tool ...

Retrieving information from a table row and using it as a parameter in the URL for an AJAX request

New to implementing ajax, JQuery, and Json in my strut2 web application. I have a table on one web page with records displayed, and the last column contains an image as shown below. Currently using an anchor tag with an image for the last column with an ac ...

How to retrieve Angular directive name using TypeScript

I have successfully implemented the following AngularJS directive: export module Directives { export class PasswordsMatch implements ng.IDirective { public static Factory(name: string) : ng.IDirectiveFactory { return () => new ...

"Failure encountered while trying to fetch JSON with an AJAX request

I am facing an issue with an ajax request. When I make the request with the property dataType: 'json', I get a parsererror in response. My PHP function returns the data using json_encode(), can someone assist me? On the other hand, when I make th ...

Retrieving JSON information from a URI in PHP without relying on cURL

Recently, I encountered a scenario where I needed to retrieve data from a URI returned in JSON format on my IIS machine with PHP. The specific URL was: The challenge was that I couldn't utilize cURL for this task. Is there an alternate method to acco ...

Adjusting the quantity of items in the blueprintjs Suggest component

In my current project, I have developed a react app using the blueprintjs visual toolkit. However, I am facing an issue where the <Suggest> box is displaying all elements from the array, instead of just the first 10 as shown in the documentation. Bel ...

Print JSON value to console

Can anyone help me figure out how to display specific json values in the console? Here's the script I'm working with: Promise.all([ fetch('https://blockchain.info/balance?active=3C6WPNa5zNQjYi2RfRmt9WUVux7V4xbDmo').then(resp => re ...

What is the best way to deliver HTML content to an ASP.NET MVC JSON function?

Here is my jQuery code that I have written along with the json function called InsertMatlabJson. However, I am facing an issue where no text is being passed to the .NET json function. function insert() { var url = '<%=Url.Content( ...

Filling the alert dialog with a JSON-based list view

Having trouble populating an alert dialog with a JSON response, but encountering the following error: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a nu ...

Having trouble retrieving JSON data using ajax

I am currently working with JSON data that is being generated by my PHP code. Here is an example of how the data looks: {"Inboxunreadmessage":4, "aaData":[{ "Inboxsubject":"Email SMTP Test", "Inboxfrom":"Deepak Saini <*****@*****.co.in>"} ...

Make sure to send individual requests in Angular instead of sending them all at once

I am looking to adjust this function so that it sends these two file ids in separate requests: return this.upload(myForm).pipe( take(1), switchMap(res => { body.user.profilePic = res.data.profilePic; body.user.coverPic = res.data.coverPic; ...

Issue with Angular: Mobile view toggle button in the navbar is unresponsive

While the dropdowns are functioning correctly in web mode, the navbar toggle isn't working as expected in small screens or mobile mode. I've been trying to figure out the issue by referring to code from CodePen that I am learning from. Despite i ...

handling text arrays in C for long integers

400000000000;499999999999;VISA; 50000000;59999999;MASTERCARD; 67000000;67999999;MAESTRO; fields: 1. Start Range 2. End Range, 3. Name. "Start Range" and "End Range" fields are allowed to have 1 to 16 characters (digits) in length. The main objective o ...

When trying to console log a selected date, the output displays as undefined

<div class='col-sm-6'> <input [(ngModel)]="date" id="date" name="date" class="form-control" required/> </div> $(function () { $('#date').datetimepicker({ format: 'DD/MM/YYYY hh:mm' } ...

What is the generic type that can be used for the arguments in

One function I've been working on is called time const time = <T>(fn: (...args: any[]) => Promise<T>, ...args: any[]): Promise<T> => { return new Promise(async (resolve, reject) => { const timer = setTimeout(() => r ...

When you want to place an image in the middle of a cell, you can easily achieve this by utilizing the addImage function

I am currently utilizing the addImage() method within the exceljs library to insert an image into a cell of an Excel file that is exported from my Angular application. While I have successfully added the image using the addImage() method, it appears in t ...

Develop a versatile factory using Typescript

For my current project, I am developing a small model system. I want to allow users of the library to define their own model for the API. When querying the server, the API should return instances of the user's model. // Library Code interface Instanc ...