Angular Differences Between Two Models - angularjs

I have an angular application which uses a significantly large shared model. Currently, when a user presses save the entire model is posted to a RESTful service. Ideally I would only like to post the fields that have changed. Since this is a shared model I do not have access to form validation states such as dirty/pristine etc. The idea I can think of is to have two models, the original and the modified and compare these.
Original Model
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"id": "123",
"number": "212 555-1234"
},
{
"id": "456",
"number": "646 555-4567"
},
{
"id": "789",
"number": "123 456-7890"
}
],
"children": [],
"spouse": null
}
Changed Model
{
"firstName": "Jane",
"lastName": "Smith",
"isAlive": true,
"age": 50,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"id": "123",
"number": "1234567890"
},
{
"id": "456",
"number": "646 555-4567"
},
{
"id": "789",
"number": "123 456-7890"
}
],
"children": [],
"spouse": null
}
Data Posted - This is what I need!
{
"firstName": "Jane",
"age": 50,
"phoneNumbers": [
{
"id":"123",
"number": "1234567890"
}
]
}
How can I achieve this? I need the changed fields including any fields called id!

You'll need something like this. Working Fiddle: https://jsfiddle.net/jyyyLaot/
function filter(obj1, obj2) {
var result = {};
for(key in obj1) {
if(obj2[key] != obj1[key]) result[key] = obj2[key];
if(typeof obj2[key] == 'array' && typeof obj1[key] == 'array')
result[key] = arguments.callee(obj1[key], obj2[key]);
if(typeof obj2[key] == 'object' && typeof obj1[key] == 'object')
result[key] = arguments.callee(obj1[key], obj2[key]);
}
return result;
}

Related

How to get certain keys from the array of objects and put them in state?

I am training to do requests to server with json.placeholder. The result of request is the array of objects with many keys.
For example the array of objects
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna#melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
},
and so on ...
But I don't need all these keys. Only to take some of them, for example name, username and id and put it in my State.
How to do that properly?
TL;DR
response = [ { "id": 1, "name": "Leanne Graham", ...}, {...}, ...]
cleanResponse = response.map(user => return {name: user.name, contact: user.email})
Here, with .map we return an object that has two property : name and contact.
We set name to user.name and contact to user.email
Anwser
I don't know much about ReactJS, but your anwser only require basic javascript :
Array.Map
You can use .map on an array to convert its elements :
nameArray= [ "George", "Alice", "Portevent" ]
presentationArray = nameArray.map(name => "My name is " + name)
// presentationArray = [ "My name is George", "My name is Alice", "My name is Portevent" ]
nameArray.map will iterate on each element. name will be equal to "George", then "Alice" etc...
Foreach element, it will be replaced with "My name is " + name (remember, name will have each different value).
Note : .map doesn't change the initial array, it just create another array (so we save it inside presentationArray
A more advanced use of map :
numbers = [1, 2, 3]
function tenToPower(n) {
return 10 ** n
}
numbers.map(number => tenToPower) // [10, 100, 1000]
numbers.map(number => {
if (number < 3) return "Failed"
else return "Valid"
}) // ["Failed", "Failed", "Valid"]
const item = data.map((user) => {
if(user.username === 'Bret'){
setName(user.name);
setUserName(user.username);
setId(user.id)
}
})

How to iterate object when it contains array of objects?

Input :
{
"id": "123",
"address": [{
"street": "5",
"city": "ameerpet",
"pin": "500073"
}, {
"street": "6",
"city": "sec",
"pin": "500020"
}]
}
Note: ["LAA001","LAA002","LAA003"] -> use this as a variable
Required output:
[{
"id": "123",
"lob": "LAA001",
"attributeText": "5"
},
{
"id": "123",
"lob": "LAA001",
"attributeText": "6"
},
{
"id": "123",
"lob": "LAA002",
"attributeText": "ameerpet"
},
{
"id": "123",
"lob": "LAA002",
"attributeText": "sec"
},
{
"id": "123",
"lob": "LAA003",
"attributeText": "500073"
},
{
"id": "123",
"lob": "LAA003",
"attributeText": "500020"
}
]
If you are using JavaScript, that should work:
var input = { "id": "123", "address": [ { "street": "5", "city": "ameerpet", "pin": "500073" }, { "street": "6", "city": "sec", "pin": "500020" }] }
var iob = ["LAA001","LAA002","LAA003"]
var output = []
input['address'].forEach((item, index) => {
var keyIndex = 0
for(const key in item){
let obj = {
"id": input['id'],
"lob": iob[keyIndex],
"attributeText": item[key]
}
output.push(obj)
keyIndex += 1
}
%dw 2.0
output application/json
var inp = ["LAA001","LAA002","LAA003"]
var inp1 = payload.address.street ++ payload.address.city ++ payload.address.pin
---
inp1 map {
id: payload.id,
lob: inp[(($$)/2)],
attributeText: $
}

How to get values from object as an array

We need to convert the object to an Array of objects and do map on the field but the field is incremental like field1, field2 which is where we got stuck.
I tried the below code:
output application/json
---
payload.main.field map(value) -> {
"name": value.name,
"age": value.age,
"location": value.location[0].country
}
Input:
{
"main": {
"field1": {
"name": "value",
"age": 20,
"address": {
"location": [
{
"country": "US",
"zipcode": 1234
},
{
"country": "US",
"zipcode": 1234
}
]
}
},
"field2": {
"name": "pqr",
"age": 23,
"address": {
"location": [
{
"country": "CA",
"zipcode": 1235
},
{
"country": "US",
"zipcode": 1234
}
]
}
},
"field3": {
"name": "abc",
"age": 22,
"address": {
"location": [
{
"country": "BU",
"zipcode": 1236
},
{
"country": "US",
"zipcode": 1234
}
]
}
}
}
}
For the above Input, Below is the expected response.
Expected Output:
{
"main": [
{
"name": "value",
"age": 20
"location": "US"
},
{
"name": "pqr",
"age": 23
"location": "CA"
},
{
"name": "abc",
"age": 22
"location": "BU"
}
]
}
For location, it will be like location[0].country when the array size is not 0 and country not null.
output application/json
---
main : payload.main pluck $ map {
"name": $.name,
"age": $.age,
"location": if( sizeOf($.address.location) !=0) $.address.location[0].country else "N/A"
}

How to create a JSON structure in ReactJS

I have a use-case to create a JSON structure in React in order to POST an API request. The JSON structure body contains objects and arrays.
Please let me know how to create it in ReactJS.
Below is the sample JSON structure that needs to be created using ReactJS:-
{
"transactionAmount": {
"currency": "INR",
"value": 1220.38
},
"transactionDate": "2020-05-18T00:00:00Z",
"tripData": {
"agencyBooked": false,
"legs": [
{
"endLocation": {
"countryCode": "IN",
"city": "Delhi",
"name": "Indira Gandhi International"
},
"startDate": "2020-05-22",
"startTime": "08:00",
"returnLeg": false,
"startLocation": {
"countryCode": "US",
"city": "San Francisco",
"name": "San Francisco International"
},
"endTime": "21:00",
"endDate": "2020-05-22",
"startLocationDetail": "none"
},
{
"endLocation": {
"countryCode": "US",
"city": "San Francisco",
"name": "San Francisco International"
},
"returnLeg": true,
"startDate": "2020-05-24",
"startLocation": {
"countryCode": "IN",
"city": "Delhi",
"name": "Indira Gandhi International"
},
"startTime": "17:00"
}
],
"segmentType": {
"category": "REQ_SEG_AIRFR",
"code": "AIRFR"
},
"selfBooked": false,
"tripType": "ROUND_TRIP"
}
}
You can simply make a JSON format like this.
const dummyObject = {
name: 'Dummy',
age: 22,
about: {
hobbies: ['soccer']
},
works: true
}

AngularJS multiple Scope needed for Autocomplete

I have an array structure like this.
[
{
"id": "1",
"name": "John",
"city": "NY"
},
{
"id": "2",
"name": "Gerold",
"city": "LA"
},
{
"id": "3",
"name": "Stuart",
"city": "Boston"
}
]
I need $scope like below for my autocomplete search.
$scope.name=["john","Gerold","Stuart"];
$scope.city=["NY","LA","Boston"];
can anyone help to get this using angularjs controller.
Thanks in Advance.!
Use MAP
$scope.users = [
{
"id": "1",
"name": "John",
"city": "NY"
},
{
"id": "2",
"name": "Gerold",
"city": "LA"
},
{
"id": "3",
"name": "Stuart",
"city": "Boston"
}
];
$scope.cities = $scope.users.map(function(obj){
return obj.city;
});
console.log($scope.cities);
You can also create a helper function that would do that for you and you don't have to define a map per function that you want, and you do it in just one run (hence just a bit faster)
Sample here ;)
var myArray = [
{
"id": "1",
"name": "John",
"city": "NY"
},
{
"id": "2",
"name": "Gerold",
"city": "LA"
},
{
"id": "3",
"name": "Stuart",
"city": "Boston"
}
]
function toScope(scopedPropertieNames, array) {
scopedPropertieNames.forEach(function(propertyName) {
if (! $scope[propertyName]) {
$scope[propertyName] = []
}
});
array.forEach(function (objecInArray) {
scopedPropertieNames.forEach(function(propertyName) {
$scope[propertyName].push(objecInArray[propertyName])
})
});
}
toScope(['name', 'city'], myArray);
console.log($scope) //{name: Array[3], city: Array[3]}
You can use MAP..
$scope.YourBigArray = [{
"id": "1",
"name": "John",
"city": "NY"
}, {
"id": "2",
"name": "Gerold",
"city": "LA"
}, {
"id": "3",
"name": "Stuart",
"city": "Boston"
}];
$scope.names = $scope.YourBigArray.map(function(object) {
return object.name;
});
$scope.cities = $scope.YourBigArray.map(function(object) {
return object.city;
});
You can do a filter to use unique things in array of names and cities..
function filterForDuplicate(things) {
return things.filter(function(item, pos) {
return things.indexOf(item) === pos;
});
}

Resources