An easy guide on transforming two arrays into JSON format with AngularJS

Here are two integer arrays along with a reason for denial:

var approvedItems = [2051, 2567];
    var deniedItems = [2053, 2569];
string deniedReason = "Naughty";

The goal is to generate the following JSON structure:

{
    "Responses": [{
        "ResponseID": 2051,
        "IsApprove": true
    },
    {
        "ResponseID": 2567,
        "IsApprove": true
    },
    {
        "ResponseID": 2053,
        "IsApprove": false
    },
    {
        "ResponseID": 2569,
        "IsApprove": false
    }],
    "Reason": "Naughty"
}

Using angular/javascript, how can I achieve this outcome?

Answer №1

What do you think of the following JavaScript code snippet?

var approvedItems = [2051, 2567];
    var deniedItems = [2053, 2569];
var deniedReason = "Naughty";

var result={
           Responses:[],
           "Reason":deniedReason
           }
approvedItems.forEach(a =>{result.Responses.push({
    "ResponseID": a,
    "IsApprove": true
   })})

 deniedItems.forEach(d =>{result.Responses.push({
    "ResponseID": d,
    "IsApprove": false
   })}
   
   console.log(result);

Answer №2

May Provide Assistance

var approvedItems = [2051, 2567];
var deniedItems = [2053, 2569];
var deniedReason = "Naughty";

var resResponse = {};
var responses = [];
if(approvedItems.length || deniedItems.length) {

    for(var ind =0; ind < approvedItems.length; ind++) {
        var response = {
            "ResponseID": approvedItems[ind],
            "IsApprove": true
        }
        responses.push(response);
    }
    for(var ind =0; ind < deniedItems.length; ind++) {
        var response = {
            "ResponseID": deniedItems[ind],
            "IsApprove": false
        }
        responses.push(response);
    }
    resResponse["Responses"] = responses;
}

if(deniedReason) {
    resResponse["Reason"] = "deniedReason";
}

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

JS await function does not wait for the completion of the request

https://i.sstatic.net/weCy0.png async function updateData(){ let stickTimes = []; await request(terryRink, function (err, res, body) { if(err) { console.log(err, "error occurred while hitting URL"); } else { le ...

Angular 9 introduces a fresh approach to compiling alternate components

I am trying to append HTML to a div and have it compile the variables, loops, and all the Angular component elements within the string. The HTML content is being uploaded via a text file. While I am aware that this can be achieved using $compile in Angular ...

Navigate to the end of the progress bar once finished

I have a solution that works, but it's not very aesthetically pleasing. Here is the idea: Display a progress bar before making an ajax call Move the progress bar to the end once the call is complete (or fails) Keep the progress bar at 90% if the aj ...

"Fixing a 'File Not Found' error in AngularJS: A step-by

I'm currently working on handling exceptions in angular js. I've managed to handle it in one scenario, but for some reason, it fails to handle it in another scenario. Why is that? Typically, when something is undefined, my $exceptionHandler catc ...

Contact the Google Finance Options API using the specified URL

When this URL is entered into the browser, it triggers an automatic download of a JSON-formatted text file containing AAPL stock option data. http://www.google.com/finance/option_chain?q=AAPL&output=json I want to retrieve this data directly into a J ...

experimenting with using protractor for testing the input type color

My input field utilizes the operating system's color picker. Is there a method available to determine if the color picker is functioning properly? <input id="accent-color" type="color" ng-model="color"> I have a hunch about what the solution m ...

Finding the identifier of an HTML element using AngularJS

I am trying to retrieve the specific id of each line and pass it to a JavaScript function that will make an HTTP request. However, I am encountering an issue when calling the function excluir(id). The parameters seem to be correct, but the alert is not tri ...

What is the method for applying a prefix to component tags in Vue.js?

Currently, I am tackling a project that was passed down to me and have noticed numerous <p-xxxx> tags scattered throughout the codebase, such as <p-page :has-something="val1" :has-another="val2" />, etc. (For example: CompName --> After a b ...

Search for documents using jQuery on the page

Here is the layout of a page: HTML <div class="alert alert-dismissable"> <div class="form-group text-center"> <div id="Section"> <div class="row"> <div class="col-md-12"> ...

JavaScript code for invoking the phone pluginInstructions for utilizing the phone plugin

Trying to implement a phone gap plugin with two parts using cordova 2.0.0 and eclipse. The java part is as follows: package org.apache.cordova; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.cor ...

Is ngWebDriver integrated with Karate UI?

Can the Karate framework be utilized with Angular-specific locators to effectively support angular JS applications? ...

Updating <h2> tags dynamically within the Ionic framework

As a complete beginner with Ionic, I've been struggling to dynamically change an H1 tag inside an ion-header-bar. Here's the HTML code snippet that I'm working with: <ion-header-bar class="cabecera bar-light"> <div class="button ...

In a Next.js application, the data retrieved from a MongoDB database is delayed compared to the data fetched from a JSON file stored

I currently have a form that utilizes data from a json file. The data is accessed in the following manner: const categoryList = require('../data/categories.json'); My plan is to switch this setup so that it retrieves data from an API which pull ...

Iterating over the IDs of div elements using jQuery loop

Currently, I am working with a bootstrap accordion and attempting to retrieve the ID and HREF values for each individual accordion using jQuery. Here is the code snippet that I have been utilizing: $('.room-loop').each(function(id){ $('. ...

Display HTML content within designated fixed-column sizes

Looking to divide the content of an HTML file into multiple fixed size columns, both in terms of height and width, then display it in a Webview. I attempted employing the CSS properties mentioned below, but couldn't get it to function as desired. -we ...

Creating custom project structures with Sails.js 0.10 generators

When looking at the upcoming Sails.js 0.10 release, one exciting feature that stands out is the addition of custom generators (currently @ rc4). You can find a migration guide on Sails' GitHub page highlighting the benefits of these generators, but i ...

How to sort by a specific split part of an array using JavaScript and jQuery?

Looking to sort an array based on a specific split part of each element. example_array = ["Zebra:Add","Pay:Cold","And:Vets","Jam:Back"] The desired outcome is: console.log(code here) // prints ["Zebra:Add","Jam:Back","Pay:Cold","And:Vets"] Note: Each p ...

Customizing styles based on screen size in Emotion Styled Components

The Emotion documentation provides guidance on creating reusable media queries that can be used within the css prop. With this feature, we can apply different styles based on various query breakpoints directly in the css prop: <div css={{ color: ...

Interactive dropdown functionality based on user selection using Material UI

I am working on a project that involves implementing 3 dropdown components with Material UI. My goal is to disable the second and third dropdowns initially, and then enable them based on the selections made in the previous dropdowns. For instance, selectin ...

How can you retrieve all JSON data from AsyncStorage using React Native?

Within the AsyncStorage of my React Native application, there are several JSON objects, each identified by a unique key id as shown below: '62834456': data: { "foo": "bar", "nicknames": [ "grizz", "example" ], ... and so on } These JSON obje ...