Using AngularJS, generate a JSON array with a specified key

Looking to create a JSON array structure with keys using AngularJS, but unsure how to push data in order to achieve this. The goal is to generate a JSON array based on the provided data below.

$scope.category = [{"id": 20, "name": "vegetable"},
    {"id": 30, "name": "fruits"}];

$scope.data = [
    { "id" : 1,"name" : "tomato", "categoryId" : 20},
    { "id" : 2,"name" : "potato", "categoryId" : 20},
    { "id" : 3,"name" : "orange", "categoryId" : 30},
    { "id" : 4,"name" : "apple", "categoryId" : 30},
    { "id" : 4,"name" : "onion", "categoryId" : 20}];

for(var i=0; i<$scope.category.length; i++) {
    for(var j=0; j<$scope.data.length; j++) {
        if($scope.category[i].id === $scope.data[j].categoryId) {

        }
    }
}

The desired output should be:

  {
    "vegetable" : [
        { "id" : 1, "name" : "tomato"},
        { "id" : 2, "name" : "potato"},
        { "id" : 3, "name" : "onion"},
    ],
    "fruits" : [
        { "id" : 3, "name" : "orange"},
        { "id" : 4, "name" : "apple"}
    ]
 }

Answer №1

In order to achieve the desired format, it is important to extract the categoryId from the JSON before injecting it into your code.

Sample Code:

$scope.myArray = [];
for(var i=0; i<$scope.category.length; i++) {
    var array = [];
    for(var j=0; j<$scope.data.length; j++) {
        if($scope.category[i].id === $scope.data[j].categoryId) {
            var index = array.push($scope.data[j]);
            delete array[index-1].categoryId;
        }
    }
    $scope.myArray[$scope.category[i].name] = array;
}

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

Is it possible to pass a variable to a text constant in Angular?

In my constant file, I keep track of all global values. Here is the content of the file: module.exports = { PORT: process.env.PORT || 4000, SERVER: "http://localhost:4200", FAIL_RESULT: "NOK", SUCCESSFUL_RESULT: "OK ...

Exiting node.js gracefully using PM2

I have a node application running with pm2, and I need to save data before the application closes. The following code works perfectly in the shell: process.on('exit', function(){ log.debug('exit'); }); process.on('SIGINT&apos ...

Perform actions while HTML5 video is in progress

I've been attempting to trigger a simple function when an HTML5 video hits a specific second mark, but so far I haven't had any success. I'm reaching out for assistance and guidance. Below is the code I have been working with: jQuery(functi ...

Passing the socket.io instance to an express route

I am currently working on developing a nodejs application that will utilize various web APIs to search for information. The goal is to send the results to the client in real-time using socket.io, with jQuery handling the front end display of the data. Wha ...

Automatically redirect to a different page upon clicking the jquery popup button

I integrated a jQuery popup feature on my website to display messages. Now, I am looking to implement a redirect to another page when the user clicks a button within the jQuery popup. However, I am unsure of how to achieve this. <script type="text/ja ...

Guide on incorporating dxTreeView with AngularJS

Hello there, I am trying to utilize the dx-tree-view component. In my Home.html file, I have included the following HTML code: <div dx-tree-view="treeViewOptions"></div> And in my HomeController.js: $scope.treeViewOptions = { binding ...

"Capture live video using the reverse camera with the HTML5-QR Code

Recently, I started utilizing a JavaScript library called html5-qrcode (https://github.com/mebjas/html5-qrcode) for scanning QR Codes directly from my browser. The performance of this library is exceptional - it's fast and seamless! https://i.sstatic ...

Can Vuex mapActions be utilized within a module that is exported?

Is it possible to utilize Vuex mapActions from an external module imported into a component? I am working on standardizing a set of functions in a vue.js web application. My goal is to import these functions into each component and pass necessary values f ...

There has been an issue with parsing the JSON file due to an invalid character found at

I keep encountering a parse error whenever I attempt to send a post request to the server. $.post("../php/user_handler.php", formData, function(data) { var result = JSON.parse(data); if(result.status === 'error') { ...

Encountering a Meteor issue during the installation of npm packages

When attempting to install cheerio through npm, I encountered a specific error message. Error: Can't set DOCTYPE here. (Meteor sets <!DOCTYPE html> for you) - line 1, file Similarly, when trying to use jsdom, I faced a parse error. Currently ...

What are the steps for updating an NPM package that was installed from a Git repository?

I'm struggling to understand how to update a package that was installed from a git repository. Let's say I have a package located at git+ssh://<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4b3bda094b3bda0b8b5b6fab1 ...

Using CoffeeScript to Invoke Methods

I'm still learning CoffeeScript and encountering some challenges with calling methods. Can someone help me out? Here is the Card model I am working with: class exports.Card extends Backbone.Model defaults: pip: '4' suit: &apos ...

The error message "ReferenceError: $ is not defined" is displayed within

My current requirement involves loading templates within an iframe, and to achieve this, I have implemented the following code: <div class="col m8 l8 s12 margin-top-30" id="hue-demo-bg-div"> <iframe id="myiframe" src="/themes/{{$themeid}}.ht ...

Looping the Connection between Socket.io and Node

I have encountered a problem with my Unity client connecting to my node server using socket.io. While the initial connection is successful and acknowledged, when I try to emit a message to the connected client, the connection seems to get reopened as if a ...

What is the best method for implementing numeric input in Vue.js?

I have experience developing web apps using Nuxt.js. I am currently trying to implement validation that excludes negative values and decimal points in all input tags (around 20-30) within the same Vue component. My approach involves injecting validation ru ...

What exactly is the purpose of the script type importmap?

Can you explain the role of <script type="importmap"> and why it has become necessary for my code to function properly? <script type="importmap"> { "imports": { "three": "http ...

What is the process for inserting a new item into a mongoose array?

I'm currently developing a confidential web application. Below is the layout I've created for the user. const itemsSchema = { name: String } const userSchema = new mongoose.Schema({ username: String, email: String, password: String, M ...

Is there a way to create a nested object literal that will return the length of

I am working with JSON data that includes different locations (sucursales) and cars for each location. How can I write a function to calculate the total number of cars across all locations? [{"sucursal": "Quilmes", "direccion&q ...

There was an error in React-Native using Native-base, as a failed prop type with an Invalid props.style key "NativeBase" was supplied to the "View"

Software Versions: React: 16.3.1 React-Native: ~0.55.2 Native-Base: ^2.8.0 Problem Alert: Warning: Failed prop type: Invalid props.style key 'NativeBase' supplied to 'View' Operating Systems: This warning keeps popping up in my r ...

Can the browser doc mode be switched frequently?

My web application is built using AngularJS, but we also have a legacy web app that functions only in quirks mode and is included via an iframe on one of our pages. The challenge is to make this legacy app work within our main browser-based application, wh ...