Using Javascript to add data to an array is not functioning properly

For some reason, I can't seem to add a new element to an array in my code. I'm not sure what's going wrong. Here is the snippet:

buildContactsCollection(primaryContact: Card){
    if(primaryContact.phones === undefined){
      primaryContact.phones = []
    }

    let primaryPhone = this.formatPhoneNumber(primaryContact.mobileRawNumber, primaryContact.mobile)

    console.log("in build collection primary phone is", primaryPhone)
    if(primaryPhone !== undefined){

      console.log("before phones are:", primaryContact.phones)
      primaryContact.phones.push({
        "type" : "personal",
        "phoneType": "mobile",
        "extn": "",
        "rawNumber": primaryPhone
      })

      console.log("after pushing:", primaryContact)
    }

The definition of the card object used is as follows:

export class Card {
private _mobile:string
private _mobileRawNumber:string
private _phones:Object[]

 get mobile():string{
        return this._mobile
    }

    set mobile(val:string){
        this._mobile = val
    }

 get mobileRawNumber():string{
        return this._mobileRawNumber
    }

    set mobileRawNumber(val:string){
        this._mobileRawNumber = val
    }

  get phones(): Object[]{
        if(this._phones === undefined)
            this._phones = []

        return this._phones
    }

    set phones(val:Object[]){
        this._phones = val
    }

Despite having a valid value for primaryPhone, the console output indicates that no new object is being pushed to the phones array.

Answer №1

When working with your Card class, remember that the private attribute to access is _phones, not just phones.

This rule also applies to handling other private attributes.

Check out the updated code snippet:

createPhoneCollection(primaryContact: Card) {
  
    if (primaryContact._phones === undefined){
      primaryContact._phones = []
    }

    let mainPhoneNumber = this.formatPhoneNumber(primaryContact._rawMainNumber, primaryContact._main)

    console.log("Main phone number in collection:", mainPhoneNumber)
    
    if(mainPhoneNumber !== undefined){

      console.log("Current phones before addition:", primaryContact._phones)
      
      primaryContact._phones.push({
        "type" : "personal",
        "phoneType": "main",
        "extn": "",
        "rawNumber": mainPhoneNumber
      })

      console.log("Phones array after adding new entry:", primaryContact)
    }
}

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

JavaScript animation for sequencing traffic lights

I have been working on completing a task that was assigned to me. (iii) Explain the organization of an array that could manage the traffic light sequence. (iv) Develop a script that utilizes the array outlined in part (iii) to create an animated display ...

What is the best way to include a   in a map function using JavaScript?

A challenge I encountered while working in React is as follows: <Grid item> { rolePriorities.map((rp, index) => ( <Chip key={index} label={rp} color="primary" sx={{ color: "whitesmoke" }} /> ...

What is the best way to retrieve the total number of options within a dynamically generated <select> element using JavaScript in JSP?

To generate a page, I use the following code: <%List<String> someList = new ArrayList<String>(); someList = SQL();%> <select id=Select> <% for (int i =0; i < someList.size(); i++) { %> <option value=<%= someLis ...

Building an efficient shopping cart feature on a website with asp.net mvc4, incorporating the use of html5 local

After receiving suggestions on my previous question, I delved into further research and began the coding process. The flowchart I am currently following is as follows: I have a products page and a partial view for the Cart. ====> When a user c ...

Node.js is unexpectedly accepting an unidentifiable image encoding

Upon calling the endpoint for an image on Postman, I am able to visually see the image here: https://i.sstatic.net/yJVZP.jpg Interestingly, when I make the same call from Visual Studio Code, the image appears in a different format shown here: https://i.ss ...

Oops! An error occurred in AngularJs: "TypeError: $scope.todos.push is not a

I am currently facing an issue while using the $http.get method to add a todo from my controller to my database. The error message "TypeError: $scope.todos.push is not a function" keeps appearing, despite trying various solutions suggested by similar quest ...

What is the process for initiating an application dynamically using second.html in Vue3?

I'm currently working on a Vue3 project. In the main.js file: import { createApp } from "vue"; import App from "./App.vue"; const app = createApp(App); import store from "./store"; app.use(store); import router from &quo ...

When you click on links and buttons, a focus outline appears

I am currently troubleshooting an issue within an existing application that relies on the use of jQuery. The problem arises when I click on any link or button on the page, causing the element to display a focus outline (such as a blue glow in browsers like ...

organizing data input into a POST array

I have developed a form that contains multiple identical sections. These sections can be dynamically added using jQuery. Each section represents one workstep involved in assembling a product, and therefore includes the same input fields (description, durat ...

Utilize JavaScript and jQuery to locate a particular character within a string and move it one position back in the sequence

Can you locate a particular character within a string and move it to the position before? For instance: Consider the following string: Kù Iù Mù The desired output is: ùK ùI ùM ...

"Request sent through Ajax can only be accepted by Localhost and specified IPs

Having an issue with my ajax post request. I want to post to a specific URL, but I also want it to accept both "localhost" and the IP address in the browser. If I set it up like this: $.ajax({ url: 'http://192.168.9.30/test/suma.php&ap ...

Building an object in React using JavaScript: A step-by-step guide to including all necessary fields

I am working on a Sign-up page where I console log the input values from each field when the 'Sign Up' button is clicked. However, I want to combine these individual values into one object in the console. If anyone can provide assistance with thi ...

What steps can I take to stop jQuery's $.getJSON function from converting my AJAX response keys into integers?

I am facing an issue where JQuery is changing the type of keys in a JSON response object from text to integer when populating a select box. This causes the response object to be reordered based on the numeric indexes, disrupting the order of the select box ...

Creating realistic water reflections in WebGL with ThreeJS

I am currently experimenting with creating a realistic water surface in WebGL using Three.js. My initial approach involves starting with a simple mirror effect and then adding displacement to achieve basic ripple effects. Here's what I have learned s ...

Utilizing Javascript to Verify the Response from $.get

How can I prevent a form submission via POST until certain conditions are met? I have a function that sends an HTML input to Python, which then checks a database to see if a user exists (returning true in JSON format if the user doesn't exist and fals ...

Having trouble establishing a web socket connection using JavaScript

I'm experiencing an issue trying to connect my web socket to an Amazon instance using a specific IP address. I've had success connecting the web socket with a different IP and port using the Google Rest Client app, but now when I try to connect w ...

Using Ajax to invoke a C# webmethod

I'm trying to call a webmethod defined in this specific class <%@ WebService Language="C#" Class="emt7anReyady.myService" %> using System; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Linq; usi ...

Is it considered acceptable to house a myriad of variables within the token object in NodeJS?

Currently working on implementing authentication with NodeJS, expressJS, mongodb and React Native. Is it acceptable to include multiple variables in the token object like shown in this example? const token = jwt.sign( { userId: user. ...

Challenge with Deploying VueJs: Chrome is stuck on the previous version and not refreshing the application

Having issues with deploying my VueJs project, a web application built on the Metronic template and utilizes Vuetify components. When publishing, I use Visual Studio Code with npm run build and upload the contents of the dist folder to my server. Encoun ...

What could be causing my function to fail <object>?

Within index.php, I am calling the function twice, which includes chart.html. index.php chart_line($valuesNight); //first call chart_line($valuesEvening); //second call ?> <?php function chart_line($jsonDataSource){ ?> < ...