The response from AngularJS $resource can be considered as both an array and an object

Recently, I obtained this JSON file:

[
{
    "name": "paprika",
    "imgSrc": "img/paprika.jpg"
},
{
    "name": "kurkku",
    "imgSrc": "img/kurkku.jpg"
},
{
    "name": "porkkana",
    "imgSrc": "img/porkkana.jpg"
},
{
    "name": "lehtisalaatti",
    "imgSrc": "img/lehtisalaatti.jpg"
},
{
    "name": "parsakaali",
    "imgSrc": "img/parsakaali.jpg"
},
{
    "name": "sipula",
    "imgSrc": "img/sipuli.jpg"
},
{
    "name": "peruna",
    "imgSrc": "img/peruna.jpg"
},
{
    "name": "soijapapu",
    "imgSrc": "img/soijapapu.jpg"
},
{
    "name": "pinaatti",
    "imgSrc": "img/pinaatti.jpg"
}
]

I was able to retrieve it successfully using a factory:

factory('getJson', ['$resource', function($resource) {
    return $resource('json/vegs.json', {}, {
      query: {method:'GET', isArray:true}
    });
  }]);

In my Controller, I managed to fetch the contents of the JSON file:

var vegs = getJson.query();
    $scope.vegs = vegs;
    console.log(vegs)
    console.log(typeof vegs)

An interesting observation is that while the first console.log displays an array of objects as expected, the second one indicates it's an "object" rather than an array.

Although I can display the .json content in my view using {{vegs}}, and even use ng-repeat, in the controller, I'm unable to access specific elements like vegs[0] or determine its length. It returns empty values.

I've been trying to figure this out for more than 3 hours now with no luck :)

Answer №1

Just sharing an observation rather than providing a definitive answer to your question. (Still getting the hang of stackoverflow, so no comments yet).

I noticed in your comment you mentioned that "The second console says it's an "object", and not an array." Remember, when using typeof on an array, it will always return "object".

There are several methods (which can be debated) to check if something is an array - for example, using Array.isArray(obj).

Check out this link for more information.

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

Troubleshooting JavaScript Date Problem with Internet Explorer 7

When I retrieve a Date from a web method, it comes in the format of "Mon Sep 30 07:26:14 EDT 2013". However, when I try to format this date in my JavaScript code like this: var d= SomeDate.format("MM/dd/yyyy hh:mm:ss tt"); //Somedate is coming from the we ...

Tips on saving additional parameters in an API URL with AngularJS

Here is my AngularJS function code: $scope.cardcall = function (cardtype) { $scope.cityname=cityname; $http({method: 'GET',url: '/api/v1/asasas&filterBy=cardNames&filterByValue='+cardtype.key}).success(funct ...

Accessing the Angular scope and making modifications using Chrome browser

I need to access the $scope value in order to update its data values via a chrome extension. I have attempted to obtain the $scope using the code below: var $scope = angular.element(document.getElementById('name')).scope() While this code wor ...

Guide on efficiently transferring fetched data from a MySQL database to a php file in JSON format

Trying to retrieve data from a MySQL table and return it as JSON in a PHP file. Below is the code snippet used for connecting to MySQL and fetching data. How can I now convert this data into JSON format? <?php $username = "user"; $password = "* ...

A guide on converting nested arrays within a JSON file into a table format in Google Sheets (possibly leveraging Javascript?)

After successfully connecting via OAuth2 to retrieve a JSON performance report for shares, I am curious about how to convert this object into a matrix format within Google Sheets. { "id": "ID-23035", "total_gain": 11795.72, "holdings": [ ...

An issue has arisen while parsing a JSON array that is set up to accept

My code works perfectly fine when I provide a single data element in my JSON file. However, when I input an array of elements, it starts displaying "undefined" on the client side. Below is the snippet of my server-side code: var app = require('expres ...

The specified object '[object Object]' is not compatible with NgFor, which only supports binding to iterable data types like Arrays

I have some code that is attempting to access objects within objects in a template. <table class="table table-striped"> <tr *ngFor="let response of response"> <td><b>ID</b><br>{{ response.us ...

Transforming Errors to JSON

Can an Exception object be converted into Json in Java 7? For example: try { //something } catch(Exception ex) { Gson gson = new Gson(); System.out.println(gson.toJson(ex)); } ...

Angular Handsontable experiencing issues when used with standard scope variables

In my Angular application, I have a scope variable named "xd" that I want to display in a table. When using a traditional table structure, everything works perfectly: <table class="table"> <tr ng-repeat="x in xd"> <th ng-bind="x.title ...

The issue persists with json_encode as it fails to display the desired JSON output

<?php include("db_connection.php"); if(isset($_POST['id']) && isset($_POST['id']) != "") { // retrieve User ID $user_id = $_POST['id']; // Retrieve User Details from database $query = "SELECT * FROM prod ...

What was the reason for the removal of the `encoding` keyword argument from json.loads() function in Python 3.9?

The json package's official documentation explains: json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)¶ As of version 3.6: The s parameter now supports bytes or bytear ...

Combining Rails API with AngularJS and IonicFramework

I'm embarking on a new project and feeling unsure about my chosen setup/approach. The project involves creating a list directory that doesn't require high computing power. My initial plan is to develop a website using Rails Api and AngularJs (al ...

Error message: `$injector:modulerr - Angular JS` - Indicates an

Currently, I am trying to delve into the world of Angular JS by taking the codeschool course "Shaping up with angular js". The instructor in the videos emphasizes the importance of wrapping code in function(){}. However, upon attempting to do so, an error ...

What is the reason for JWT tokens using Base64 encoding instead of UTF-8?

RFC 7515 Section 3 states: Both the JWS Protected Header, JWS Payload, and JWS Signature are base64url encoded in both serializations because JSON does not have a direct way of representing arbitrary octet sequences. What is the limitation that prevents ...

Discover how to extract JSON data from a webpage even when the response is "None"

I need to retrieve data maps from their API, which are in JSON format. This is the code I have written: r = requests.get(url) if r.ok: soup = BeautifulSoup(r.content, 'lxml') soup.status_code j = json.loads(str(soup)) However, an e ...

Refresh the angular form after submitting data

I am currently working on an angular form to input data into a database. My framework of choice is angular-fullstack by yeoman. After successfully submitting the data, I encounter an issue where clearing the form values doesn't allow me to add new en ...

Conduct a unit test to verify that a function successfully connects to an API and accurately stores the retrieved data in a variable

Currently, I am working on creating a unit test for my writing and JavaScript code. This area is still challenging for me, so I am in the process of learning how to do it correctly. The specific function I am focusing on makes an API call and then assigns ...

The specified property is not recognized by the type in TypeScript

I have set up a basic form with validation in Ionic 2. The form functioned properly when I used 'ionic serve' but encountered issues when running 'ionic run'. My suspicion is that the problem lies within my TypeScript code, specifically ...

What is the best method for displaying the date/time with timezone in AngularJS?

While utilizing the AngularJS filter date, I have incorporated the following code snippet: var date = new Date("09 apr 2015 12:00:50 UT"); $filter('date')(date, "dd MMM yyyy hh:mm:ss a Z"); The current output is: 09 Apr 2015 08:19:04 PM + ...

Unable to extract a particular value from a JSON data structure

This situation has been on my mind for a good couple of hours now. I have this json object with example values like so: { "events": [ { "id": 64714, "live": false, "start": "1399117500", "league_ ...