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

Converting data into a hierarchical structure for a JSON file

Can someone assist me in parsing this specific file for the Gene Ontology (.obo)? I need guidance on how to accomplish this task. I am currently working on a project that involves creating a visualisation in D3. To achieve this, I require a JSON format "t ...

What is the size limit for JSON requests in Node.js?

I am seeking information about the req object in nodeJS. Let's say I have a code that sends data in JSON format to my server using an AJAX POST method. Now, imagine a scenario where a user manipulates my client code to send an excessively large JSON f ...

Choose a particular character in a text that corresponds with a regular expression in Javascript

I am looking to replace the symbols < and > within the text. I have constructed a regular expression as follows: (<span[^>]+class\s*=\s*("|')subValue\2[^>]*>)[^<]*(<\/span>)|(<br(\/*)>) This ...

Email responses containing unidentifiable values

Currently, I am working on implementing AJAX for my contact form to send form data to the server. The objective is to have the server email me the user's information extracted from the input fields. However, I'm encountering an issue where the f ...

How to Store Values from a ReadStream in an Array

I'm currently attempting to use a stream and the async/await keywords with the fast-csv library in order to read a CSV file synchronously. Unfortunately, the function I've written doesn't seem to be producing the expected output. My assumpt ...

Send an AJAX request to redirect to a different page on a PHP server

After collecting data from JavaScript, my page transfers it to PHP and then MySQL. The issue arises when I want the page to redirect to different pages based on the database content. I attempted to use the header function, but it only displayed the entire ...

Unable to transform node lacking a body

I am attempting to execute the sample code in the react-testing-library to test react hooks. However, it's encountering an issue on this particular line: testHook(() => ({count, increment} = useCounter({ initialCount: 2 }))) It appears to be rela ...

Vue-router: the browser tries to open a <router-link> element as if it were a local file

Having some trouble with Vue-router - when I click on a navigation link, the desired component briefly displays before the browser tries to open it as a file. For instance, clicking on the "Badger!" link results in the browser attempting to open a local f ...

Order a collection of period-separated namespace strings into a JSON string with nested structures using C#

Is there a way to organize a collection of dot-notation namespace strings into a nested JSON structure? For example: var string1 = "example.string.1"; var string2 = "example.string.2"; var string3 = "example.anotherstring.1"; Which would be sorted into: ...

The ng-style directive is not applying the value from the scope

I have a few different views and I want to be able to adjust the width of the container depending on which view I am currently in. <!-- This is our main container area for displaying the various views --> <div class="container" ng-style="{ ' ...

Error: The strategy for authentication is not recognized as "login" - Express and Passport

I am currently experimenting with a basic MEAN stack tutorial I found online. The technologies involved are: Node.js Express.js Passport.js Below is the code snippet for the application file: app.js var express = require("express"); var mongoose = req ...

Looking to include an additional field in mongoose documents when generating a JSON object in a Node.js application?

var commentSchema = new Schema({ text: String, actions:[{actionid:String, actiondata:String}], author: String }) When retrieving the records, I require a count for action = 1. The desired outcome is to include this count as an additional key ...

Run JavaScript code whenever the table is modified

I have a dynamic table that loads data asynchronously, and I am looking for a way to trigger a function every time the content of the table changes - whether it's new data being added or modifications to existing data. Is there a method to achieve th ...

Guide on transmitting data from a child component to a parent object in Vue.js?

When I attempt to utilize a child component with custom form inputs and emit those values to the parent component, I encounter an issue where one input value disappears when another input value is entered. Let me showcase some code: Child Component <tem ...

Unlock the potential of JavaScript by accessing the local variable values in different functions

I've been struggling for days to find a solution to this issue... https://i.stack.imgur.com/KDN7T.jpg https://i.stack.imgur.com/tOfCl.jpg The image above illustrates the challenge I'm facing - trying to apply data values from elsewhere to the ...

Steps for converting a JSON response into a .json file.Steps to transform a

I am looking to create a .json file within my local project directory. My goal is to store the response from a fetch API call, which is an array of objects, into a .json file. Here is the code snippet I am working with: ts : getRecords(){ this.serv ...

Using promises and the fetch function to connect to a database

I am attempting to utilize promises with the fetch() function in order to access MongoDB from the front-end, but I am encountering some issues. var Promise = () => ( new Promise((resolve, reject) => { //perform certain actions, make requests ...

Can you explain the concept of being "well-typed" in TypeScript?

The website linked below discusses the compatibility of TypeScript 2.9 with well-defined JSON. What exactly does "well-typed" JSON mean? As far as I understand, JSON supports 6 valid data types: string, number, object, array, boolean, and null. Therefore, ...

Obtaining the jqXHR object from a script request loaded within the <head> tag using the <script> tag

Is it possible to retrieve the jqXHR object when a script loaded from a script tag within the head tag? function loadScript(url){ const script = document.createElement("script"); script.src = url; // This line will load the script in the ...

Troubleshooting Highcharts container selection problem on Nexus 7 running version 4.2.1

Having a problem with Highcharts on my Nexus 7. When I touch the chart, the entire thing gets selected with a blue overlay, but this doesn't happen on other devices like the Nexus 4. Even when I try accessing demos from Highcharts website, the issue ...