Combining two JSON responses using AngularJS

$scope.addUserJson = $scope.adduser;

console.log($scope.addUserJson);

Output

Object {"username":"Mik911","firstname":"Mike","lastname":"Angel","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="563b3f3d16313b373f3a7835393b">[email protected]</a>"}

$scope.usergroup = $scope.usergroupmodel;

console.log($scope.usergroup);

Output

[Object{"grpid":"1","username":"Vikram911","firstname":"Vikram","lastname":"Doe","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef998684af88828e8683c18c8082">[email protected]</a>","gender":"Male",
"description":"BLAH BLAH","phone":"5858585"},{"grpid":"2","username":"Varun091","firstname":"Varun","lastname":"Doe",
"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83f5e2f1f6edc3e4eee2eaefade0ecee">[email protected]</a>","gender":"Male","description":"BLAH BLAH","phone":"898989"}]

Merging two objects

$scope.object = angular.toJson(angular.merge({}, $scope.usergroup, $scope.addUserJson));

console.log($scope.object);

Output

[{"grpid":"1","username":"Vikram911","firstname":"Vikram","lastname":"Doe","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a4d2cdcfe4c3c9c5cdc88ac7cbc9">[email protected]</a>","gender":"Male",
"description":"BLAH BLAH","phone":"5858585"},{"grpid":"2","username":"Varun091","firstname":"Varun","lastname":"Doe",
"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a7d1c6d5d2c9e7c0cac6cecb89c4c8ca">[email protected]</a>","gender":"Male","description":"BLAH BLAH","phone":"898989"}]

Combining the above two JSON responses to create a final result as shown below:

{"username":"Mik911","firstname":"Mike","lastname":"Angel","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c3aeaaa883a4aea2aaafeda0acae">[email protected]</a>","grpid":["1,2"]}

Answer №1

Merging an object with an array or extracting only one field from the merge is not a straightforward task.

To set the `grpid` of the `addUserJson` object manually in just one line, you can utilize the JS `array map` function like this:

$scope.addUserJson.grpid = $scope.usergroup.map(function(grp) { return grp.grpid; });

Answer №2

I have enhanced usability by treating the $scope.addUserJson as an array...

If it will never be an array, please inform me so I can revert it back to a single JSON object.

var app = angular.module('myApp',[]);

app.controller('myCtrl',function($scope){

$scope.usergroup = [{"grpid":"1","username":"Vikram911","firstname":"Vikram","lastname":"Doe","email":"[email protected]","gender":"Male",
"description":"BLAH BLAH","phone":"5858585"},{"grpid":"2","username":"Varun091","firstname":"Varun","lastname":"Doe",
"email":"[email protected]","gender":"Male","description":"BLAH BLAH","phone":"898989"}]


$scope.addUserJson = [{"username":"Mik911","firstname":"Mike","lastname":"Angel","email":"[email protected]"}];
var result = [];

// console.log($scope.usergroup);
for(x in $scope.addUserJson){
// console.log($scope.addUserJson.username +"=="+ $scope.usergroup[x].username);
var temp=[];
for(y in $scope.usergroup){

if($scope.addUserJson[x].username.localeCompare($scope.usergroup[y].username)){
temp.push($scope.usergroup[y].grpid);
}
}
if(temp.length>0){
var result1 = $scope.addUserJson;
result1[0].grpid = temp;
result = result1[0];
temp=[];
}
}


console.log(result);


});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
</body>

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

Managing multiple sets of radio buttons using the useState hook

Within my renderUpgrades-function, I handle the options of an item by including them in radio-button-groups. Each item has multiple options and each option has its own radio-button-group. Typically, a radio-button-group can be managed using useState, wit ...

Using ReactJS to Send Props Between Two Components

Currently, in my project, I am working on a payment form that conditionally renders 2 Stripe elements (PaymentRequestForm.js & CheckoutForm.js). While I have successfully passed down props from the main form component FullfillRequest.js to PaymentRequestFo ...

Stopping PHP execution when an Ajax request is aborted

I want the browser to wait for notifications, but stop waiting if a link is clicked. To achieve this, I have created a PHP script with a while loop that ends when an event occurs and then returns that event. PHP require 'required.php'; ignore_ ...

Retrieve data from an ASP.NET Web API endpoint utilizing AngularJS for seamless file extraction

In my project using Angular JS, I have an anchor tag (<a>) that triggers an HTTP request to a WebAPI method. This method returns a file. Now, my goal is to ensure that the file is downloaded to the user's device once the request is successful. ...

Incompatibility in Parse Cloud Code syntax leading to query failure

We are in need of an aggregation pipeline that utilizes various stages like: addFields, lookup, group, and unwind. However, there seems to be a discrepancy when converting the MongoDB Compass syntax into Parse Cloud Code JavaScript calls, as we are not ach ...

Can an additional height be added to the equalizer to increase its height?

Is it feasible to append an additional 35px to the height determined by Foundation Equalizer? For instance, if Equalizer computes a height of 350px, I would like to increase it by 35px. This means that the resultant style should be height: 385px; instead ...

What causes the DateTime value to change when data is passed to a controller action? Exploring the behavior with AngularJS and ASP.Net Web API 2

When transmitting data from the client side to the server side, the two properties of the DateTime type, "ReviewStartDate" and "ReviewEndDate," are changing. These two DateTime properties do not change on the client side, but their values are altered on th ...

Missing transitive dependencies have been identified within the node_modules directory when using npm

In my software development journey, I am working on two npm projects - one called X and the other called Y. Let's say that X relies on angular and has it specified as a dependency in its package.json file. To establish a connection between X and Y, I ...

`problem with moment.js incorrectly identifying the day of a given date`

I'm currently working with a field that has the value 03-01-2020, which is in the DD-MM-YYYY date format. However, when I apply the code moment.utc(document.getElementById('date').value, "DD-MM-YYYY HH:mm:ss").toDate(), I noticed that the re ...

Ways to host static content in ExpressJS for specific directories and exclude others

I need to configure my ExpressJS server to serve static files from specific paths only, excluding others. For example, I want to serve static files from all paths except /files where I only need to manipulate a file on the server. Currently, my code looks ...

What is the best way to upload an object in React using fetch and form-data?

Currently, I am facing an issue where I need to send a file to my express app as the backend. The problem lies in the fact that my body is being sent as type application/json, but I actually want to send it as form-data so that I can later upload this file ...

These JS and Perl scripts may encrypt the same data, but they generate different results. Isn't it expected for them to produce identical output?

Two different programs, one in Javascript and the other in Perl, were designed to accomplish the same task with identical input data. Nevertheless, the output generated by these programs varied. The issue stemmed from using JavaScript on the client side to ...

Locate the div element containing specific text and remove the text from the

Is there a way to locate a div that contains specific text and remove only that specific text from the div? For instance: <div> DeleteText <span>Something text</span> <div>Something span inner text </div> </div> I am l ...

Issue with border spacing functionality

I'm having some difficulty with my border spacing in CSS. No matter what size I specify, it doesn't seem to have any effect. I just want to use a border for the top line. Here is my CSS: p { border-spacing: 5000px; text-align: right; ...

Transferring JSON data from Django for visualization on a D3 graph

I'm currently working on customizing a D3 bar graph found at http://bl.ocks.org/3885304 to accommodate JSON data from Django. In Django, I have a variable that holds JSON formatted data like this: [{"score": 1, "color": "blue"}, {"score": 5, "color": ...

Copying an instance in JavaScript - The copy method

Is there a way to easily duplicate all properties and methods of a class instance? class A { get prop1() { return 1; } get prop2() { return 2; } doStuff() { return this.prop1 + this.prop2; } } class B extends A { get prop1() { ...

Retrieve vuex state in a distinct axios template js file

I have encountered an issue with my Vue project. I am using Vuex to manage the state and making axios requests. To handle the axios requests, I created a separate file with a predefined header setup like this: import axios from 'axios' import st ...

What is the proper way to confirm the authenticity of a captcha code

hey there, I'm struggling with my captcha code. The issue is that it still accepts wrong captchas when entered in the input box. Can someone guide me on how to validate the wrong captcha entry? Here's my form code: <p class="Captcha" style=" ...

Continuously running loop to retrieve data

I've been working on a function that retrieves data from the backend and then assigns it to the state for display in a web browser. Although everything seems to be functioning correctly, I've noticed that every time I make a request, the function ...

Address the snack bar problem

In my quest to create a custom snackbar, I have encountered a minor issue with setting and deleting session variables in Node.js. While using global or local variables works well for accessing data on the client side, there is a chance of issues when multi ...