receiving an object as the return value in AngularJS

To access locfrnd in the code snippet below, follow these steps: I have created an Array named PlaceCollection containing 2 elements.

  1. place
  2. locfrnd, which is an array

While I was able to successfully access place, I encountered an error when trying to access locfrnd.

var ctry = $scope.country;
var frnds = [];

angular.forEach($scope.Friend, function (friend) {
    var eachFriend = {
        name: friend
    };
    frnds.push(eachFriend);
});

var record = {
    place: ctry,
    locFrnd: frnds
};

$scope.placeCollection.push(record);

//The issue arises with the following code resulting in 'object object' alerts
for (var j = 0; j < $scope.placeCollection.length; j++) {
    alert($scope.placeCollection[j].locFrnd);
}

Answer №1

To properly display the contents of your array, you can utilize the JSON.stringify method as illustrated below:

var locations = [{place: 'ABC', friendLocation: 'XYZ'}, {place: 'abc', friendLocation: 'xyz'}];
alert(JSON.stringify(locations));

It's important to note that if your friendLocation is an array and you use alert on it directly, the output would be [object Object].

Answer №2

This method is also applicable

   for (let k = 0; k < $scope.placeCollection.length; k++) {
        let locFriendArr = $scope.placeCollection[k].locFrnd;
            locFriendArr.map(function(element){
                                            console.log(element.name })
                                         }
}

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

jQuery doesn't have the capability to convert this data into JSON format

I have some code that I want to convert into JSON format: var locationData = []; locationData['lat'] = position.coords.latitude; locationData['long'] = position.coords.longitude; locationData['address']['road'] = da ...

Integrating fresh components into a JSON structure

I've been attempting to insert a new element into my JSON, but I'm struggling to do it correctly. I've tried numerous approaches and am unsure of what might be causing the issue. INITIAL JSON INPUT { "UnitID":"1148", "UNIT":"202B", "Sp ...

eliminating reliance on promises

I understand the importance of promises, however I am faced with a challenge as I have multiple old functions that currently operate synchronously: function getSomething() { return someExternalLibrary.functionReturnsAValue() } console.log(getSomething( ...

Is it true that Javascript does not allow for saving or outputting actions?

After coming across this question, I discovered a way to extract a specific element from a Google translate page using Javascript. However, I also learned that it is nearly impossible to directly save something to the clipboard in Javascript without user i ...

What is the procedure for modifying the height of a button in HTML?

I wanted to add a flashing "Contact Us" button to the menu bar of my website to immediately attract people's attention when they visit. Here is the javascript code I used: <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /&g ...

Tips for navigating a list of areas in JavaScript

Currently, I am in the process of learning Javascript and I have a query regarding browsing an area list using Javascript. Could someone kindly guide me on whether it is possible to achieve this, and if so, how? Below is the HTML code snippet I am workin ...

Learn about Angular8's prototype inheritance when working with the Date object

In my search for a way to extend the Date prototype in Angular (Typescript), I stumbled upon a solution on GitHub that has proven to be effective. date.extensions.ts // DATE EXTENSIONS // ================ declare global { interface Date { addDa ...

Retrieve the Most Recent Matching Date within an Array

In my mongoDB database, I am searching for datasets with expired date values. When I say expired, I mean that the timestamp of the last element in an array is older than a certain interval from the current timestamp (determined by a category). Each datase ...

What is the best way to utilize JavaScript variables that are declared on index.html/index.jsp in Vue.js?

Just starting out with Vue.js and I recently finished developing a Vue.js app using the terminal. I then deployed it on a Java web application and noticed that everything works fine when running it as is. However, I now need to pass a csrftoken to my Vu ...

What is the process of performing numerical calculations using jQuery?

I need to deduct certain input values from the total price. Here's the code snippet: $('.calculate-resterend').click(function(e) { e.preventDefault(); var contant = $('.checkout-contant').val(); var pin = $('.che ...

Transforming a Processing (cursor) file into an interactive webpage

I have created a custom cursor using Processing and now I want to incorporate it into my website. Is there a way to convert the cursor into a .java file so that I can include it in my HTML file? ...

Creating bidirectional data binding with isolated scopes in AngularJS - a comprehensive guide

directive('confButton', function () { return { restrict: 'EA', replace: false, scope: { modalbtntext: '@', btntext: '@&ap ...

Retrieving a component's property within its event handler in React

In the React component, there is a need to create multiple instances with different key values passed as arguments to the onClick event handler. However, the issue arises when using a variable such as 'value' in a for loop, as it ends up taking t ...

NodeJS: Increasing memory consumption leads to system failure due to recursive scraping

Currently, I am utilizing a GET URL API in NodeJS to extract various data by looping through the months of the year across multiple cities. For each set of parameters such as startDate, endDate, and location, I invoke a scrapeChunk() function. This functio ...

Is it possible to modify the labels on CKEditor's toolbar elements?

Initializing CKEditor in the following manner: function init() { $( ".ckeditor" ).ckeditor( { format_tags: 'h3;p', toolbar: [ [ "Source", "-", "Bold", "Italic" ], [ "Link", "Unlink" ], [ "Blockquote", "F ...

What could be causing the malfunction in my 'sort' function? I have thoroughly checked for errors but I am unable to locate any

Exploring the world of JavaScript objects to enhance my understanding of functions and object manipulation. I have created a program that constructs an Array of Objects, each representing a person's 'firstName', 'middleName', and & ...

Tips for sharing JSON data between JavaScript files

Here is the initial script setup to utilize static .json files for displaying and animating specific content. The code provided is as follows: var self = this; $.getJSON('data/post_'+ index +'.json', function(d){ self.postCa ...

Dynamic jQuery Carousel

Is there a jQuery slider that can adapt to different screen sizes and handle images of varying widths? Appreciate any insights! ...

What could be causing the unexpected text display in my shiny app despite using html tags and bootstrap?

Here is a simple example that illustrates the error I am experiencing: library(shiny) run_with_enter <- ' $(function() { var $els = $("[data-proxy-click]"); $.each( $els, function(idx, el) { var $el = $(el); var $proxy = $("#" + $el.data("proxyCl ...

What is the best method to override the CSS transition effect with JavaScript?

I am trying to implement a CSS transition where I need to reset the width of my box in advance every time my function is called. Simply setting the width of the box to zero makes the element shrink with animation, but I want to reset it without any animati ...