Unable to insert a JSON object into an Array

This might appear to be a duplicate, but it's not. None of the solutions I've tried have worked.

Within my angular module, I have a list:

this.checkedInterviews = []

Followed by a function that does the following:

var interviewModel = {
                        interviewId: self.pendingInterviews[i].id,
                        status: self.pendingInterviews[i].status,
                        location: self.pendingInterviews[i].location,
                        start: self.pendingInterviews[i].start,
                        hideCheck: null
                    };
 this.checkedInterviews.push(JSON.stringify(interviewModel));

The error message

Cannot read property 'push' of undefined
is returned. Any insights on what could be causing this issue?

Answer №1

var checkedIntervews = []
var interviewModel = {};
checkedIntervews.push(JSON.stringify(interviewModel));
console.log(checkedIntervews);

(function arrayPush() {
this.checkedIntervews = [];
var interviewModel = {};
this.checkedIntervews.push(JSON.stringify(interviewModel));
console.log(this.checkedIntervews);
})();

You should consider attempting the following:

var checkedIntervews = []
var interviewModel = {};
checkedInterviews.push(JSON.stringify(interviewModel));
$scope.checkedInterviews = checkedInterviews; //In case AngularJS is being used since it's mentioned in the question

IMPORTANT: Make sure to utilize this if all of this code resides within the same function. It should work within the global scope as well. An IIFE is only used here to separate out the scopes.

The above snippet includes both scenarios described.

If you are unsure about what this refers to in your context, please clarify your question for better assistance.

Answer №2

When using distinct functions, the reference to this in the second function corresponds to a separate object.

Answer №3

It appears that the second function is utilizing a different instance of this.

Within an Angular Module, you have the option to assign this to a certain variable and then attempt to retrieve it from the second function.

For example:

var vm = this;
vm.checkedInterviews = [];

Subsequently, within the function, you should access it like so:

vm.checkedInterviews.push();

Answer №4

Give this a shot Check out this functional fiddle

  var myApp = angular.module('myApp',[]);

  function MyCtrl($scope) {
  $scope.checkedInterviews = [];
  $scope.pendingInterviews = [{'id':1,'status':'pending','location':'abc','start':'start'}];
  for(i= 0; i < $scope.pendingInterviews.length; i++){
      var interviewModel = {
                      interviewId: $scope.pendingInterviews[i].id,
                      status: $scope.pendingInterviews[i].status,
                      location: $scope.pendingInterviews[i].location,
                      start: $scope.pendingInterviews[i].start,
                      hideCheck: null
      };
      console.log(interviewModel);
      $scope.checkedInterviews.push(JSON.stringify(interviewModel));
    }
  console.log($scope.checkedInterviews);
}

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

Refreshing iOS UiCollectionView with a custom UiCollectionViewLayout

Currently, I am facing a small issue while attempting to implement a custom UiCollectionViewLayout into my project. The objective is to fetch JSON data from the web and display it in a UICollectionView. However, when I integrate my own layout instead of us ...

A guide to toggling the check/uncheck status of a list box by clicking on a checkbox using

I am using a div and CSS id to control the checkbox check and uncheck functionality, but I am not getting the desired outcome from my source code Step 1: By default, the checkbox is unchecked and the listbox is disabled Step 2: When the checkbox is check ...

How can I design a trapezoid with see-through borders and background?

Using various CSS border tricks, it's possible to create a trapezoid shape. Additionally, setting the border-color to rgba(r,g,b,a) can make it transparent. However, is there a way to create a trapezoid with both transparent borders and background? ...

Adjust puppeteer window dimensions when running in non-headless mode (not viewport)

Is there a way to adjust the browser window size to match the viewport size in Chrome(ium)? When only setting the viewport, the browser can look awkward if it is not running headfully and I want to visually monitor what's happening within the browser ...

Encountering difficulties with the functionality of Google Places API

I am attempting to incorporate the autocomplete functionality of Google Places API into a text field. Below is the code I have implemented: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script> <script ...

The function signature '() => void' cannot be assigned to a variable of type 'string'

Encountering an issue in Typescript where I am attempting to comprehend the declaration of src={close} inside ItemProps{}. The error message received reads: Type '() => void' is not assignable to type 'string'. Regrettably, I am ...

Ways to restrict a JavaScript object from being sent through ajax requests

I have developed an application that utilizes JSON to send messages through ajax. Here is the JavaScript object used for this purpose: var message = { "message_by": colmn[0].innerHTML, "message_date": new Date(), "message_recipients": [ { ...

Unable to view the refreshed DOM within the specifications after it has been altered

For my current project, I am working on writing a functional spec that involves using Mocha/JSDOM and making assertions with 'chai'. The specific use case I am tackling is related to the function called updateContent: When this function is exec ...

Utilize the synchronization feature of ES6 Promises in Jasmine with the then/catch method

I have an angular controller that needs to be tested. This controller utilizes a service to fetch data from a server, and the service returns ES6 Promises. function MyController($scope, MyService) { $scope.doSomething = function () { MyService.foo() ...

Limiting input to specific characters is effective on Chrome, but unfortunately does not function on Firefox

This code snippet is designed to restrict user input to lowercase letters from a-z, numbers from 0-9, and the dash character "-". While it functions correctly in Chrome, it does not allow any input in Firefox. What could be causing this issue? $('#sl ...

Exploring techniques to iterate through this specific JSON data within an Angular frontend

I am looking for assistance in looping the data below into a 'Select dropdown' using Angular 10. The data consists of all the States in India along with their districts. I have retrieved this information from the internet, but I am unsure how to ...

Creating objects in separate JavaScript files and including them in the main file, along with their

Following the creation of a config.js file with an object named contextTokenObject, modifications and additions need to be made to this context object from another file (specifically when creating a passport strategy). In the 'passport.js' file, ...

Activate lightbox on click to swap image source temporarily

I have implemented the Materialize CSS "Material Box" lightbox plugin, but I am facing an issue. I want all the thumbnails to be uniform in size, and when clicked, the full photo should be displayed. Currently, I am using the onclick function to change th ...

What is the best way to establish and concentrate on a fresh component in AngularJS?

I am working on a form that has a dynamic number of inputs, which is controlled by AngularJS. <body ng-app="mainApp" ng-controller="CreatePollController" ng-init="init(3)"> <form id="createPollForm"> <input class="create-input" ...

Stop the child component from activating the parent's onClick event

Trying to implement Material-ui within a React project, I am facing an issue with the <IconButton> component and its onClick behavior conflicting with the parent component's behavior. Specifically, I want the <IconButton> to add an item to ...

Obtaining the decoded JSON value

I'm encountering an issue trying to access an object (stdClass) after using json_decode. The trouble seems to be related to the use of a hyphen (-) as part of the key. Here's the code snippet in question: $a = array('body'=>array(& ...

Angular 8 does not allow for the assignment of type '{}' to a parameter

I have a unique approach for managing errors: private handleErrors<T>(operation = 'operation', result?: T) { return (error: any): Observable<T> => { console.error(error); this.record(`${operation} failed: ${error.m ...

Manipulating Objects and Arrays

When I retrieve data from a database query in Node.js using Postgres with Knex, I get an array of objects structured like this: (condensed version) [ { tvshow: 'house', airdate: 2017-02-01T00:00:00.000Z }, { tvshow: ' ...

What is the method for a Greasemonkey script to divide a link into three interconnected links?

My goal is to use Greasemonkey to link Redmine issue numbers found in cgit commit messages to their respective issues or projects. The cgit commit message HTML source looks like this: <a href='/editingmodule/commit/?id=49e4a33e0f8b306ded5'&g ...

Choosing several buttons in typescript is a skill that every programmer must possess

I need help with selecting multiple buttons in TypeScript. The code I tried doesn't seem to be working, so how can I achieve this? var input = document.getElementById('input'); var result = document.getElementById('result'); v ...