Remove object array duplicates and store non duplicate values in array - javascript

I need to merge an array of deliveries that have notes, how would I remove the duplicate object but still keep the note string and store it in an array for the non duplicated object
Key begin the delivery number:
"data": [
{
"deliveryNumber": "0000001",
"deliveryDate": "2021-10-01T00:00:00.000Z",
"dateBeginProcess": null,
"dateFinishedProcess": null,
"status": "",
"notes": "Note 1"
},
{
"deliveryNumber": "0000001",
"deliveryDate": "2021-10-01T00:00:00.000Z",
"dateBeginProcess": null,
"dateFinishedProcess": null,
"status": "Ready",
"notes": "Note 2"
},
{
"deliveryNumber": "0000002",
"deliveryDate": "2021-10-01T14:21:00.000Z",
"dateBeginProcess": null,
"dateFinishedProcess": null,
"status": "Ready",
"notes": null
}
]
into
"data": [
{
"deliveryNumber": "0000001",
"deliveryDate": "2021-10-01T00:00:00.000Z",
"dateBeginProcess": null,
"dateFinishedProcess": null,
"status": "Ready",
"notes": ["Note 1", "Note 2"]
},
{
"deliveryNumber": "0000002",
"deliveryDate": "2021-10-01T14:21:00.000Z",
"dateBeginProcess": null,
"dateFinishedProcess": null,
"status": "Ready",
"notes": null
}
]

You can use Array.prototype.forEach() to loop over the notes array. If a note is encountered twice add their notes together.
const notes = [
{
"deliveryNumber": "0000001",
"deliveryDate": "2021-10-01T00:00:00.000Z",
"dateBeginProcess": null,
"dateFinishedProcess": null,
"status": "",
"notes": "Note 1"
},
{
"deliveryNumber": "0000001",
"deliveryDate": "2021-10-01T00:00:00.000Z",
"dateBeginProcess": null,
"dateFinishedProcess": null,
"status": "Ready",
"notes": "Note 2"
},
{
"deliveryNumber": "0000002",
"deliveryDate": "2021-10-01T14:21:00.000Z",
"dateBeginProcess": null,
"dateFinishedProcess": null,
"status": "Ready",
"notes": null
}
]
let filteredArray = []
notes.forEach(note => {
let noteFound = filteredArray.find(el => el.deliveryNumber === note.deliveryNumber)
if(noteFound){
// not first encounter
// add notes together
noteFound.notes.push(note.notes)
}else{
// first encounter
// make notes an array
note.notes = [note.notes||'']
filteredArray.push(note)
}
})
console.log(filteredArray)

Related

Add new property to react state

I am trying to add a new property to the state "initialTags". However, I do not know how to do that. I have tried to loop through the object to set the new property, however it didnt work. Also, the setState it all in a same function, but since setState is async, I am unable to setState on the same state after my first setState statement.
Initializing the state:
this.setState({ initialTags: [...tempTarget] }, () => console.log("initTags == ", this.state.initialTags));
Array of Object after setState:
[
{
"name": "AQS",
"projectId": "MTYzMDE1MzU3NjA3My10ZXN0MTA",
"projectName": null,
"isUserForAllProject": false
},
{
"name": "ED",
"projectId": null,
"projectName": null,
"isUserForAllProject": null
},
{
"name": "PAID",
"projectId": null,
"projectName": null,
"isUserForAllProject": null
},
{
"name": "QS",
"projectId": null,
"projectName": null,
"isUserForAllProject": null
}
]
The New property that needs to be added in the Object:
[
{
"name": "AQS",
"projectId": "MTYzMDE1MzU3NjA3My10ZXN0MTA",
"projectName": null,
"isUserForAllProject": false,
"return": []
},
{
"name": "ED",
"projectId": null,
"projectName": null,
"isUserForAllProject": null,
"return": []
},
{
"name": "PAID",
"projectId": null,
"projectName": null,
"isUserForAllProject": null,
"return": []
},
{
"name": "QS",
"projectId": null,
"projectName": null,
"isUserForAllProject": null,
"return": []
}
]
EDIT: SOLUTION
this.setState({ initialTags: [...tempTarget.map(item => ({...item, returnVal: []}))] })
this.setState((prev) => {
return {
...prev,
initialValues: prev.initialValues.map((item) => {
return {
...item,
returnValue: []
};
})
};
});
You shoudn't use return as it is a keyword.

Property 'emailAddress' does not exist on type 'BaseModel'.ts

I have a feature that calls the api from the service , Now I wanted to do for each on the res.items and check the emailAddress but I cant loop through it and I am receiving an error Property 'emailAddress' does not exist on type 'BaseModel'.ts which I dont understand on why.
What seem to be the issue that causes this one ? why is that the for each not working ? Any ideaS?
this is the sample data from the _transactionUserPageEvent
#Component A service
getUserProfileTableDropdown(
id: number,
page: number,
pageSize: number,
searchString: string,
sortKey: string[],
sortOrder: string[]
): Observable<PagedModel> {
const params = new HttpParams()
.set('id', id.toString())
.set('page', page.toString())
.set('pageSize', pageSize.toString())
.set('searchString', searchString)
.set('sortKey', JSON.stringify(sortKey) || '')
.set('sortOrder', JSON.stringify(sortOrder) || '');
return this.httpRequestService.get<PagedModel>(
`${apiBaseUrl}/table/profiles`,
params
);
}
#Component A TS Code
private _transactionUserPageEvent() {
this.isTransactionUserLoading = true;
this.transactionUserTable.data = [];
this._userProfileService.getUserProfileTableDropdown(
this.accountId,
this.transactionUserTable.pageIndex + 1,
this.transactionUserTable.pageSize,
this.searchTransactionUserInput.nativeElement.value,
this.transactionUserTable.sortParams,
this.transactionUserTable.sortDirs
)
.pipe(
finalize(() => this.isTransactionUserLoading = false)
)
.subscribe({
error: err => this._notificationService.showError(err),
next: res => {
console.log("new users" , this.selectedNewUser)
this.transactionUserTable.totalElements = res.totalItemCount;
this.transactionUserTable.data = res.items as UserProfileDropdownDto[];
this.totalData = res.totalItemCount;
this.currentDisplayedData = res.lastItemOnPage;
res.items.forEach(item => {
if(item.emailAddress && selectedNewUser.findIndex(x => x.emailAddress === item.emailAddress) !== -1){
item.checked = true;
}
});
},
complete: noop
});
}
#base-model.ts
export class BaseModel {
// createdStr: string;
// createdByUser: AuditUser;
// modifiedStr: string;
// modifiedByUser: AuditUser;
}
export class PagedModel {
firstItemOnPage: boolean;
lastItemOnPage: boolean;
totalItemCount: number;
items: BaseModel[];
constructor(isFirstPage: boolean, isLastPage: boolean, totalItems: number, itemList: BaseModel[]) {
this.firstItemOnPage = isFirstPage;
this.lastItemOnPage = isLastPage;
this.totalItemCount = totalItems;
this.items = itemList;
}
}
#dto user code
export class UserProfileDropdownDto {
id: number;
fullName: string;
roleDisplay: string;
firstName:string;
lastName:string;
isChecked: boolean = false;
}
I'm not sure, about the behavior of your task, but I assumed that you want to fill a dropdown from API response right?
For that you created this model UserProfileDropdownDto & you want to fill this model as an Array from API response, after that you may consume this inside your html,
By Keeping this scenarios in my mind, this below solution may help you
Please update your UserProfileDropdownDto model like below
export class UserProfileDropdownDto extends BaseModel {
id: number;
fullName: string;
roleDisplay: string;
firstName:string;
lastName:string;
isChecked: boolean = false;
emailAddress: string;
....
}
Just make sure that your UserProfileDropdownDto model, must has the properties of API response.
Now make correction in your PagedModel model like this,
export class PagedModel {
firstItemOnPage: boolean;
lastItemOnPage: boolean;
totalItemCount: number;
items: UserProfileDropdownDto[];
constructor(
isFirstPage: boolean,
isLastPage: boolean,
totalItems: number,
itemList: UserProfileDropdownDto[]
) {
this.firstItemOnPage = isFirstPage;
this.lastItemOnPage = isLastPage;
this.totalItemCount = totalItems;
this.items = itemList;
}
On Based of your comment! I have write down solution for another problem
Current Result
let data = {
"id": 0,
"name": "adas",
"description": "dasdas",
"status": "",
"teamMembersDto": [
{
"id": 120098,
"fullName": "xsc#gmail.com xsc#gmail.com",
"roleDisplay": null,
"firstName": "xsc#gmail.com",
"lastName": "xsc#gmail.com",
"emailAddress": "xsc#gmail.com",
"phoneNumber": "12",
"companyName": "xsc#gmail.com",
"title": "xsc#gmail.com",
"lastLogin": null,
"createdDate": "09/08/2021 7:44:56 am",
"isVerified": false,
"roleDto": null,
"status": "Active",
"securityRole": "Unlicensed User",
"lastLoggedIn": "",
"teamCount": 0,
"transactionRoleList": null
},
{
"id": 40091,
"fullName": "yukre#gmail.com yukre#gmail.com",
"roleDisplay": null,
"firstName": "yukre#gmail.com",
"lastName": "yukre#gmail.com",
"emailAddress": "yukre#gmail.com",
"phoneNumber": "232423",
"companyName": "yukre#gmail.com",
"title": "3434",
"lastLogin": null,
"createdDate": "06/08/2021 12:35:32 pm",
"isVerified": false,
"roleDto": null,
"status": "Active",
"securityRole": "Unlicensed User",
"lastLoggedIn": "",
"teamCount": 0,
"transactionRoleList": null
}
],
"accountId": 4
}
Expected Result
let data = {
"id": 0,
"name": "adas",
"description": "dasdas",
"status": "",
"teamMembersDto": [
{
"id": 0,
"fullName": "xsc#gmail.com xsc#gmail.com",
"roleDisplay": null,
"firstName": "xsc#gmail.com",
"lastName": "xsc#gmail.com",
"emailAddress": "xsc#gmail.com",
"phoneNumber": "12",
"companyName": "xsc#gmail.com",
"title": "xsc#gmail.com",
"lastLogin": null,
"createdDate": "09/08/2021 7:44:56 am",
"isVerified": false,
"roleDto": null,
"status": "Active",
"securityRole": "Unlicensed User",
"lastLoggedIn": "",
"teamCount": 0,
"transactionRoleList": null,
"memberId": 120098
},
{
"id": 0,
"fullName": "yukre#gmail.com yukre#gmail.com",
"roleDisplay": null,
"firstName": "yukre#gmail.com",
"lastName": "yukre#gmail.com",
"emailAddress": "yukre#gmail.com",
"phoneNumber": "232423",
"companyName": "yukre#gmail.com",
"title": "3434",
"lastLogin": null,
"createdDate": "06/08/2021 12:35:32 pm",
"isVerified": false,
"roleDto": null,
"status": "Active",
"securityRole": "Unlicensed User",
"lastLoggedIn": "",
"teamCount": 0,
"transactionRoleList": null
"memberId": 40091
}
],
"accountId": 4
}
Solution
data.teamMembersDto = data.teamMembersDto.map((item) => {
let id = item.id;
return {
...item,
id: 0,
memberId: id
}
});

How do I loop JSON response to get specific data in Javascript or GAS

I Have an JSON response from an external API. Problem is i only know how to log the response but not manipulate it. In this case, I need to get some information from the response and loop through the entire response to show the list of all the users. Here is my code so far. Its not a good one, but this what i could do with my minimal javascript skills.
};
var response= UrlFetchApp.fetch(url, options)
var call= JSON.parse(response.getContentText());
var people=call.data;
var user= {}
user.ID = call.data[1].id;
user.Email = call.data[1].email;
user.Name= call.data[1].display_name;
Logger.log(user)
}
Sample response:
"data": [
{
"id":00126,
"first_name": "Test",
"last_name": "Test",
"archived": false,
"display_name": "Test Test",
"email": "test#test.com",
"termination_date": null,
"mobile_phone": null,
"office_phone": null,
"deleted_at": null,
"deleted": false,
},
"data": [
{
"id":00126,
"first_name": "Test",
"last_name": "Test",
"archived": false,
"display_name": "Test Test",
"email": "test#test.com",
"termination_date": null,
"mobile_phone": null,
"office_phone": null,
"deleted_at": null,
"deleted": false,
},
You can use Array.prototype.map to iterate through data and return required information only from the object
let data = [
{
"id": 00126,
"first_name": "Test",
"last_name": "Test",
"archived": false,
"display_name": "Test Test",
"email": "test#test.com",
"termination_date": null,
"mobile_phone": null,
"office_phone": null,
"deleted_at": null,
"deleted": false,
}]
let res = data.map(({id, email, display_name}) => ({ID: id, Email: email, Name: display_name}));
console.log(res)
If ES6 is not supported
var res = data.map(function(userData) {
return {ID: userData.id, Email: userData.email, Name: userData.display_name}
});

How to parse JSON files from text with node.js?

So I"m trying to parse out an html response into JSON for accessible objects.
This is my router
router.get('/yammer', function(req, res) {
var userFields;
var yammerCode = req.query.code;
var getYammerFieldsAddress = "http://www.yammer.combalwh;eoiahweg";
getYammerFieldsAddress += yammerCode;
console.log(getYammerFieldsAddress);
httpreq.get(getYammerFieldsAddress, function(err, response) {
if (err) return console.log(err);
console.log(response);
var yammerUserInfo = response.body;
var blah = yammerUserInfo.user;
console.log(blah);
But the info comes like this
{
"user":
{
"timezone": "Hawaii",
"interests": null,
"type": "user",
"mugshot_url": "https://www.yammer.com/yamage-backstage/photos/…",
"kids_names": null,
"settings": {
"xdr_proxy": "https://stagexdrproxy.yammer.com"
},
"schools": [],
"verified_admin": "false",
"birth_date": "",
"expertise": null,
"job_title": "",
"state": "active",
"contact": {
"phone_numbers": [],
"im": {
"provider": "",
"username": ""
},
"email_addresses": [
{
"type": "primary",
"address": "test#yammer-inc.com"
}
]
},
"location": null,
"previous_companies": [],
"hire_date": null,
"admin": "false",
"full_name": "TestAccount",
"network_id": 155465488,
"stats": {
"updates": 2,
"followers": 0,
"following": 0
},
"can_broadcast": "false",
"summary": null,
"external_urls": [],
"name": "clientappstest",
"network_domains": [
"yammer-inc.com"
],
"network_name": "Yammer",
"significant_other": null,
"id": 1014216,
"web_url": "https://www.yammer.com/yammer-inc.com/users/…",
"url": "https://www.yammer.com/api/v1/users/101416",
"guid": null
},
"access_token": {
"view_subscriptions": true,
"expires_at": null,
"authorized_at": "2011/04/06 16:25:46 +0000",
"modify_subscriptions": true,
"modify_messages": true,
"network_permalink": "yammer-inc.com",
"view_members": true,
"view_tags": true,
"network_id": 155465488,
"user_id": 1014216,
"view_groups": true,
"token": "ajsdfiasd7f6asdf8o",
"network_name": "Yammer",
"view_messages": true,
"created_at": "2011/04/06 16:25:46 +0000"
},
So it seems there are multiple objects coming through. I've tried accessing them from the response body, I've also tried JSON.stringify() and I can't access it. ANy ideas? Thanks!
Replace this line
var yammerUserInfo = response.body;
With
var yammerUserInfo = JSON.parse(response.body);
and it should work properly. :)
Try
var jsonObject = JSON.parse(response.body);

Loop over Json using Jquery

Below is my Json Data received from Ajax response.
{
"error": {
"errorCode": "0001",
"errorText": "SUCCESS"
},
"responselist": [
{
"count": 2,
"event": [
{
"startDate": null,
"eventId": 1234,
"eventName": "Interview",
"modifiedUser": "User",
"eventTypeCode": "1",
"eventVenue": null,
"eventSpecialInst": "isnsdf",
"eventStatusCode": "OP",
"eventLangCode": "Eng",
"eventDesc": "sdfsadfsd",
"fromEmailId": "Abcd#apple.com",
"rsvpDeadline": 5,
"canceledInd": "yes",
"canceldEmailText": "sdfasdfasdfasfasdfasdfasdf",
"daysToWaitlistLastCall": 5,
"daysToReminderAdmin": 6,
"daysToReminderEvent": 3,
"daysToReminderInvitation": 2,
"endDate": null,
"venueAddrLine1": null,
"venueAddrLine2": null,
"venueAddrLine3": null,
"cityCode": null,
"stateCode": null,
"appId": null,
"modifiedDate": "2010-12-16",
"countryCode": null,
"zipCode": null,
"user_id": null,
"updateFlag": "R"
},
{
"startDate": null,
"eventId": 4321,
"eventName": "Seasonal Hiring",
"modifiedUser": "User",
"eventTypeCode": "1",
"eventVenue": null,
"eventSpecialInst": "isnsdf",
"eventStatusCode": "OP",
"eventLangCode": "Eng",
"eventDesc": "sdfsadfsd",
"fromEmailId": "Abcd#apple.com",
"rsvpDeadline": 5,
"canceledInd": "yes",
"canceldEmailText": "sdfasdfasdfasfasdfasdfasdf",
"daysToWaitlistLastCall": 5,
"daysToReminderAdmin": 6,
"daysToReminderEvent": 3,
"daysToReminderInvitation": 2,
"endDate": null,
"venueAddrLine1": "KFC",
"venueAddrLine2": "The Forum",
"venueAddrLine3": "Koramangala",
"cityCode": "Bangalore",
"stateCode": "Karnataka",
"appId": null,
"modifiedDate": "2010-12-16",
"countryCode": "India",
"zipCode": "560040",
"user_id": null,
"updateFlag": "R"
}
]
}
]
}
Using below code to extract information inside event object. But I am not able to do it. Need guidance.
$.ajax({ url:"<%=request.getContextPath()%>/service/showInvitedEvents/21",
dataType:"json",
success: function(jsonData)
{
alert("Inside response success");
$.each(jsonData.responselist.event,function(i,item)
$.each(Employees,function(i,item)
{
alert('Iteration is' + i);
var teventName = item.eventName;
var teventVenue = item.eventVenue;
var tstartDate = item.startDate;
var tendDate = item.endDate;
var tstarend = tstartDate +" - "+ tendDate ;
$("#eventTable tbody").append("<tr><td><a id="+teventName+i+" href=<%=request.getContextPath()%>/service/session/1234>"+teventName+"</a></td><td>"+teventVenue+"</td><td>"+tstarend+"</td></tr>");
});
First of all you can't loop over jsonData.responselist.event. jsonData.responselist is an array so either need to make a double loop or if you always know there is one and only one item in responslist you could loop over jsonData.responselist[0].event
For the rest of it I'm not sure why you have this row:
$.each(Employees,function(i,item)
Looks like a misstake to as it isn't valid there(the syntax is wrong and it hides both i and item from the real each).
What is the purpose of the following line in your code:?
$.each(Employees,function(i,item)
Try removing it and see what happens.

Categories