How can I effectively retrieve data and store it in an object and array using AngularJS?

I am currently working on extracting data from a spreadsheet and storing it in an array. After storing the data in JavaScript variables, I need to store these variables as an object in my array. Below is the code snippet:

this.json = function(){
        jQuery.getJSON("http://cors.io/?u=https://spreadsheets.google.com/feeds/list/1l4XTKaLZihj5WDRuZJE5Y7RQ7Cr7SD_-tH0ctwhizWc/od6/public/values?alt=json").success(function(data) {
            console.log(data.feed.entry);
            
            for (var i = 0; i < data.feed.entry.length; i++) {

                var id = data.feed.entry[i].gsx$id.$t;
                var name = data.feed.entry[i].gsx$name.$t;
                var price = data.feed.entry[i].gsx$price.$t;
                var notcompatiblewith = data.feed.entry[i].gsx$notcompatiblewith.$t;

                this.parts[i] = {"id": id, "name": name, "price": price, "comp": notcompatiblewith, "canAdd": true, "added": false};    
            };
        });
    };

I invoke the function this.json in my HTML using ng-init="myctrl.json()" and it works perfectly. However, when I check the console on inspect element, I encounter the error: 'Uncaught TypeError: Cannot set property '0' of undefined'

The desired formatting of my array upon initialization:

{
    id: 1,
    name: 'vitamine A',
    price: 3,
    canAdd: true,
    added: false,
    comp: [2, 5]
},
{
    id: 2,
    name: 'vitamine B',
    price: 5,
    canAdd: true,
    added: false,
    comp: [1, 3]
},
{
    id: 3,
    name: 'vitamine C',
    price: 2,
    canAdd: true,
    added: false,
    comp: [2]
},
{
    id: 4,
    name: 'Opium',
    price: 20.95,
    canAdd: true,
    added: false,
    comp: []
},
{
    id: 5,
    name: 'steroids',
    price: 12.5,
    canAdd: true,
    added: false,
    comp: [1]
}

Edit: The array parts is initialized under my controller as shown below:

var parts = [];

and declared in my controller like this:

this.parts = parts;

Answer №1

Whenever you invoke this, it points to jQuery. Consequently, parts is not a valid entity.

Furthermore, your approach is incorrect. It is advisable to employ a service for this functionality, with Angular's $http module being utilized for AJAX requests.

Your current method does not align with proper Angular usage.

For further information, refer to: https://docs.angularjs.org/guide/services

Answer №2

To start, make sure to set up the this.parts variable as an empty Array:

this.json = function(){
    jQuery.getJSON("http://cors.io/?u=https://spreadsheets.google.com/feeds/list/1l4XTKaLZihj5WDRuZJE5Y7RQ7Cr7SD_-tH0ctwhizWc/od6/public/values?alt=json").success(function(data) {
        console.log(data.feed.entry);
        this.parts = []; // <-- Add this line
        // code continues...
    });
};

Additionally, consider using the push method of Array instead of setting values directly like this.parts[i] = ...:

this.parts.push({"id": id, ... });

Answer №3

Have you given this a shot?

this.parts[i].push({"id": id, "name": name, "price": price, "comp": notcompatiblewith, "canAdd": true, "added": false}); 

The reason being:

this.parts[i] = {"id": id, "name": name, "price": price, "comp": notcompatiblewith, "canAdd": true, "added": false};  

This will result in assigning only one value to the array. Each time the array is updated, it will replace the previous value with the latest one.

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

Toggle the visibility of tooltips based on a condition with uib-tooltip

I am looking for a way to toggle the functionality of a tooltip on a button. I attempted to disable it with the following code snippet: <button type="button" uib-tooltip="test" tooltip-is-open="false"> </button> However, the tooltip stil ...

Is there a way I can retrieve the appended link text upon clicking?

Hello everyone! I have successfully created my own jQuery/JavaScript auto complete search suggestions div. I have implemented a feature where it pulls in an XML dictionary full of words and uses regular expressions to suggest matches based on user input. H ...

Encountering an issue while attempting to fetch a value from a nested object property with VueJS Interpolation

I'm struggling to properly display nested arrays in Vue JS. Below is a snippet of my JSON data: { "id": 1, "slug": "test-page", "banner": { "title": "banner title", "subTitle": "my sub title", "hasSubTitle": false, "hasClass": " ...

Tips on implementing v-show within a loop

Hey @zero298, there are some key differences in the scenario I'm dealing with. My goal is to display all the items in the object array and dynamically add UI elements based on user input. Additionally, v-if and v-show function differently (as mentione ...

change array to key value pairs in PHP

Here is a sample array: $arr=array( 'key1'=>'value1', 'key2'=>'value2', 0=>array( 'sub1_key1'=>'sub1_value1', 'sub1_key2'=>'sub1_value2', ...

Delete entries in table based on user-provided criteria

Hello there, I'm new to this community and seeking some assistance. I am currently learning jQuery/Javascript and have encountered a problem that has me stumped. The issue arises with a table where rows are generated based on a user-selected number f ...

Combining the power of Angular with a Vanilla JS web application

Seeking your expertise. Situation We are transitioning from a legacy Vanilla JS webapp to Angular. Our plan is to gradually replace isolated components while adding new functionality as separate Angular apps, all within a timeframe of 6-12 months. Challe ...

Unable to make a post using vue.js

I am facing an issue while trying to submit form data using "vue-resource" in my code. The error message I receive mentions a problem with the use of this method alongside vue-cli and vuetify. Error [Vue warn]: Error in v-on handler: "TypeError: this.$h ...

Utilizing Javascript for a Stopwatch/Countdown in the Format: 00:00:00

I am currently working with this block of code: function startStopwatch() { vm.lastTickTime = new Date(); $interval.cancel(vm.timerPromise); vm.timerPromise = $interval(function() { var tickTime = new Date(); ...

What is the method for resetting dropdown values to null with ng-change in AngularJS?

There is a dropdown called Drop-down A. Depending on the option selected from this dropdown, new dropdowns will appear. For example, selecting option 1 from Drop-down A will display 2 new dropdowns. Similarly, selecting other options wil ...

Using Nest JS to create two instances of a single provider

While running a test suite, I noticed that there are two instances of the same provider alive - one for the implementation and another for the real implementation. I reached this conclusion because when I tried to replace a method with jest.fn call in my ...

How can we make sure the selected tab opens in jQuery tabbed content?

I'm trying to make my tabbed content open on a specific tab by changing the URL. I remember seeing something like this before but can't seem to find it! Here's the fiddle I created: http://jsfiddle.net/sW966/ Currently, the default tab is ...

An error is thrown in Three.js stating that the array index 'i' is undefined at line 180, using TransformControls

While working with loaded .STL Files in Three.js using TransformControls, I'm experiencing an issue. Whenever I mouse hover or use the transformControls, my console logs "TypeError: array[i] is undefined three.js:180:9". Is anyone familiar with this e ...

Developing Angular dynamic components recursively can enhance the flexibility and inter

My goal is to construct a flexible component based on a Config. This component will parse the config recursively and generate the necessary components. However, an issue arises where the ngAfterViewInit() method is only being called twice. @Component({ ...

Whenever I press a button, my card holder gradually slides downwards

I'm facing an issue with my code and I'm unsure whether it's related to CSS or JavaScript. Whenever I click the button on my page, my card-container2 moves downward unexpectedly. Here is the snippet of my code: HTML: <div class="car ...

Tips for maintaining the functionality of IFrame?

I am encountering an issue with tracking clicks on a div that contains an IFrame. While the tracking functionality works, it seems to interfere with the IFrame's functionality. Is there a way to resolve this and make both functionalities work simultan ...

Can we find a method to incorporate multicolored borders?

I currently have a td element with the following CSS styling: td { border-bottom: 3px solid aqua; } I want to be able to click on these cells and change their color, similar to the images linked below: https://i.sstatic.net/5DscU.png Is there a way ...

What is the best way to apply a Javascript function to multiple tags that share a common id?

I am experimenting with javascript to create a mouseover effect that changes the text color of specific tags in an HTML document. Here is an example: function adjustColor() { var anchorTags = document.querySelectorAll("#a1"); anchorTags.forEach(func ...

In JavaScript, using window["functionName"](arguments) will result in a TypeError message saying that the function does not exist

When trying to execute an AJAX function based on the active tab in my application, everything works smoothly when I trigger the function after specific events. However, I encounter difficulties when attempting to call the function using a dynamically gener ...

MongoDB Update is only impacting the first element within the array

I have been working on a challenge involving a Mongo updateMany() query. Let me share an example of a document found in my collection: { "CurrentVersion": 3, "EntryHistory": [ { "State": 0, ...