Leveraging angularjs forEach iterations

When working with AngularJS, I am receiving the following JSON in my $scope:

$scope.someStuff = {
      "id": 2,
      "service": "bike",
      "min": "22",
      "per": "100",
      "tax": "1",
      "categoryservices": [
        {
          "id": 32,
          "category": {
            "id": 1,
            "name": "software"
          }
        },
        {
          "id": 33,
          "category": {
            "id": 2,
            "name": "hardware"
          }
        },
        {
          "id": 34,
          "category": {
            "id": 3,
            "name": "waterwash"
          }
        }
      ]
    }

I am looking to extract only the category names using an AngularJS forEach loop.

The desired output should be:

[{"name":"software"}, {"name":"hardware"}, {"name":"waterwash"}]

Answer №1

If you want to transform elements in an array, you can utilize the Array.map() method.

The map() function generates a new array by applying a specified function to each element of the original array.

$scope.someStuff.categoryservices.map((x) => { return { name: x.category.name}}) 

var obj = {
  "id": 2,
  "service": "bike",
  "min": "22",
  "per": "100",
  "tax": "1",
  "categoryservices": [{
      "id": 32,
      "category": {
        "id": 1,
        "name": "software"
      }
    },
    {
      "id": 33,
      "category": {
        "id": 2,
        "name": "hardware"
      }
    },
    {
      "id": 34,
      "category": {
        "id": 3,
        "name": "waterwash"
      }
    }
  ]
};

console.log(obj.categoryservices.map((x) => {
  return {
    name: x.category.name
  }
}))

Answer №2

To utilize the map method, simply provide a callback function as an argument.

const data = { "id": 2, "service": "bike", "min": "22", "per": "100", "tax": "1", "categoryservices": [ { "id": 32, "category": { "id": 1, "name": "software" } }, { "id": 33, "category": { "id": 2, "name": "hardware" } }, { "id": 34, "category": { "id": 3, "name": "waterwash" } } ] }   
let resultArray = data.categoryservices.map(function({category}){
  return {'name' : category.name}
});
console.log(resultArray);

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

How can I eliminate text using regular expressions?

Greetings, I am seeking assistance with content removal using regular expressions. Below is the regular expression code I have written: reg = reg.replace(/\|.*?(\|)/g, ''); Input: One-1|two-2|Three-3|Four-4|Five-5 Six-6|Seven-7|Eig ...

Issue: Images are not displaying in jQuery slideshow.Possible cause: There

I'm currently working on developing a slideshow using jQuery and HTML. However, I've encountered an issue where only one image is displaying while the other slides are not showing up at all. I've been troubleshooting this problem but haven&a ...

Personalized Icons for Google Maps. (Designed for iPhone)

I am currently working on a project where I am designing a website specifically for iPhones. The main functionality of the site is to find the latitude and longitude of a certain location and display it on a Google map. I already have all the necessary det ...

Utilize Ajax to open and close an HTML tag within separate div elements

I am facing a challenge in my project where I have to dynamically open and close a form using ajax. The form needs to be opened within a div, and then closed in another div below it like the following: Opening form (header div) $('#header').h ...

Activate Auto Navigation Feature on Mouseover using jQuery

I have a series of divs that cycle automatically to display their contents one after the other every few seconds. The same content is also displayed when the corresponding link is hovered over. The functionality is working correctly, but I would like to ...

What is the best way to combine two arrays of negative numbers into a single array?

I am trying to merge negative numbers from two arrays. Here is my approach: I add elements to an array, and then attempt to merge elements that are less than zero into a new array. This is the code snippet I have been working on: int main() { int arr ...

What advantages does incorporating a prefix or suffix to a key provide in React development?

Is there any advantage to adding a prefix or suffix to the key when using an index as a key in React (in cases where no other value such as an id is present)? Here's an example: const CustomComponent = () => { const uniqueId = generateUniqueId( ...

Set up the ObjectMapper globally (using @Bean or a similar method) to handle parsing from the "data" section

Despite the abundance of Jackson questions on various platforms, I have dedicated countless hours to searching for a solution without success. My current challenge involves consuming a REST web-service that delivers data in JSON format. The response could ...

Unusual issue encountered with mapView functionality in CreateForm

Today I'm here with an issue related to react-native, specifically a strange behavior I encountered. The problem is closely connected to Map. When I click to select a place on the Map and set a marker, it works fine. However, when I try to move the ma ...

Skipping the validation of a variable in a return statement with Angular and Javascript

Is there a way to exclude level a.3 from the return in the completion form if a.3 is undefined? scope.isValid = function() { return a.1 && a.2 && a.3; }; ng-disabled="!isValid()" ...

Updating the default value of a MUI TextField: Step-by-step guide

I am in the final stages of completing my form, but I have encountered an issue when trying to display the current user's name in the defaultValue variable of the TextField from MUI. If the value starts as ""/null, or essentially empty, the ...

Error in Origin Access Control detected in the XMLHttpRequest

We encountered the following error when using the REST API: "No 'Access-Control-Allow-Origin' header is present on the requested resource." Here is my code snippet: function get_XmlHttp() { var xmlHttp = null; if(window.XMLHttpRequest ...

Error: Failed to convert string value "new" to an ObjectId at field "_id" in the "Model" model

I'm currently diving into Mongoose for a project in the Web Developer Bootcamp (the one on Udemy) and encountered an issue with it. It seems like a simple fix, but here are the Express routes included in index.js: app.get('/products/new', (r ...

What is the best way to retrieve the output of MongoDB's collection.aggregate() within a NodeJS callback function?

In my database, I have a users collection with the following data: { "_id" : ObjectId("5b29ba37cd0b1726068731c3"), "name" : "Gym Dog", "profilePicUrl" : "https://i.imgur.com/mPStaKV.png", "totalProgress" : { "goal" : 300, "progress ...

304 status code is returned by Couchapp when requesting a view

I'm currently in the process of developing a straightforward couchapp CRUD application. However, when I attempt to fetch a view, CouchDB returns a 304 response. Surprisingly, the same view in Futon displays documents without any issues. Below is an ex ...

problem when testing html file using javascript jasmine

Is it necessary to have a .js suffix when testing an html file with the D3.js javascript library using jasmine, or can HTML files also be tested with jasmine? ...

Tips for SOAP UI Assertion: Ensuring correctness of the Total attribute and its corresponding value

After conducting extensive research on both Google and Stackoverflow, I was unable to find any useful information regarding my query. Therefore, I have decided to reach out and post my question here. The data is being returned to me in JSON format from an ...

What is the best way to trigger a function in Vue.js when a click event occurs on Google Maps?

In my Nuxt.js app in SPA mode, I am utilizing the Google Maps API and I'm aiming to trigger a function in Vue.js methods from the gmap click event. When attempting this.createInfoWindow(), it became apparent that this does not refer to the VueCompone ...

commenting system through ajax across multiple web pages

Experimenting with the webcodo comment system has led me to this URL: Database table: "comments" CREATE TABLE IF NOT EXISTS `comments` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(40) NOT NULL, `email` varchar(60) NOT NULL, `comment` te ...

Creating a JavaScript automated slideshow with multiple instances of loops and/or setInterval running simultaneously?

Currently, I am facing a challenge while trying to create a basic automated slideshow from scratch. Though I have successfully built manual slideshows in the past, automating them is proving to be more complex. I started by experimenting with a for loop st ...