forEach nested to match - javascript

Here i made a code.
let StaffParsed = JSON.parse(params.StaffJson);
console.log(StaffParsed)
Here is the result below fo console log.
Object
cellPhoneNo: "1234567890"
createdBy: "1"
createdDate: "2020-05-09T17:26:31.743"
email: "ravi#email.com"
fax: "1234567890"
firstName: "Ravi"
id: 1004
lastName: "Nikam"
phoneNo: "1234567890"
profilePic: ""
sendEmail: false
sendPhone: false
status: "3"
title: "Mr."
type: "2"
updatedBy: "1"
updatedDate: null
username: "ravi109"
__proto__: Object
I have this model created here is the code below.
public StaffModel : Staff = new Staff();
console.log(this.StaffModel);
Its console log result is below.
Staff
CellPhoneNo: 0
CnfPassword: ""
CreatedBy: ""
CreatedDate: null
Email: ""
Fax: 0
FirstName: ""
FormStaffGroup: FormGroup {validator: null, asyncValidator: null, pristine: true, touched: false, _onCollectionChange: ƒ, …}
Id: null
LastName: ""
Password: ""
PhoneNo: 0
ProfilePic: ""
SendEmail: false
SendPhone: false
Status: "0"
Title: ""
Type: "0"
UpdatedBy: ""
UpdatedDate: null
UserName: ""
__proto__: Object
enter code here
Now i want to match with the above first object list with the second list and update the second list model, so far i have tried this code.
Object.keys(StaffParsed).forEach(function(keyParsed) {
Object.keys(this.StaffModel).forEach((keyModel: string) => {
if(keyParsed == keyModel){
keyParsed = this.StaffModel[keyModel];
}
});
});
But in return, it shows error like this .

Your problem is this part:
... .forEach(function(keyParsed) {
Object.keys(this.StaffModel)
this does not propagate into functions like that. As such, the this inside the function has a different value from the this in the outside function.
If you want the function to inherit the this of the outside scope, use an arrow function instead. ((keyParsed) => { instead of function(keyParsed) {)

In your code this in this.StaffModel[keyModel] may refer to the function not global.
Try this:
let that = this;
Object.keys(StaffParsed).forEach(function (keyParsed) {
Object.keys(that.StaffModel).forEach((keyModel: string) => {
if (keyParsed == keyModel) {
keyParsed = that.StaffModel[keyModel];
}
});
});

Related

How to omit `undefined` column in javascript or typescript when serialization object

I have object like:
Person {
id: '75c37eb9-1d88-4d0c-a927-1f9e3d909aef',
user: undefined,
title: 'Mr.',
first_name: 'somebody',
last_name: 'body',
belong_organization: undefined,
expertise: [],
contact: undefined
}
when I do serialization I use loadsh omit function like:
toJSON() {
return _.omit(this, ['contact']);
}
What I want to do is omit the property which is undefined, since the error:
`undefined` cannot be serialized as JSON.
The column is dynamically, can not predict certain column like I did.
instead of omit, pickBy and omitBy are preferable for this :
var person = {
id: '75c37eb9-1d88-4d0c-a927-1f9e3d909aef',
user: undefined,
title: 'Mr.',
first_name: 'somebody',
last_name: 'body',
belong_organization: undefined,
expertise: [],
contact: undefined
};
const newPerson= _.pickBy(person, v => v !== undefined);
console.log(newPerson);
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.20/lodash.min.js"></script>
JSON.stringify will omit undefined properties without any special logic.
console.log(JSON.stringify({
id: '75c37eb9-1d88-4d0c-a927-1f9e3d909aef',
user: undefined,
title: 'Mr.',
first_name: 'somebody',
last_name: 'body',
belong_organization: undefined,
expertise: [],
contact: undefined
}, null, 3));
It might be the problem when you define the class. I reproduced and it still works. Below snippet could help you
class Person {
constructor(props) {
Object.assign(this, props)
}
toJSON() {
return _.omit(this, ["contact"])
}
}
const person = new Person({
id: "75c37eb9-1d88-4d0c-a927-1f9e3d909aef",
user: undefined,
title: "Mr.",
first_name: "somebody",
last_name: "body",
belong_organization: undefined,
expertise: [],
contact: undefined,
})
console.log(person.toJSON())
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.20/lodash.min.js"></script>

JSON Stringfy only a few properties

I have this object:
{
name: "",
email: "",
phone: "",
protocol: "",
area: "",
subject: "",
message: "",
validation: this.validator.valid()
}
I wanna convert it to JSON, but I do not want the validation property on it.
I've already tried the following:
const test = JSON.stringify(this.state);
delete test.validation;
Any other approach?
JSON.stringify takes a replacer callback you can use. The replacer function takes a key k and the value v being stringified as parameters. Returning undefined will have the effect of not including the key in the final result:
state = {
name: "",
email: "",
phone: "",
protocol: "",
area: "",
subject: "",
message: "",
validation: "some val"
}
const test = JSON.stringify(state, (k, v) => k != 'validation' ? v : undefined);
console.log(test)
Note: used like this it will remove the validation key from any child objects as well, which may or may not be what you want.
It will work.
const { validation, ...rest } = this.state;
JSON.stringify(rest);
UPDATE - I found a different solution
It's very simple, in fact. I've discovered the solution here.
The following lines solved my problem:
const formSubmit = JSON.stringify(this.state, ['name', 'email', 'phone', 'protocol','area','subject', 'message']);
If you put an undefined, JSON.stringify will skip it:
const yourState = {
name: "",
email: "",
phone: "",
protocol: "",
area: "",
subject: "",
message: "",
validation: true,
}
const copy = {
...yourState,
validation: undefined,
};
console.log(JSON.stringify(copy));
Also, you can not perform a delete from JSON.stringify because it is a string an not an object literal.

setState not setting state variable React

I'm trying to set state variable to response data from api call but unable to do so . I have division array in responseJson which i'm trying to set to divisions array in state. I'm getting the responseJson values on console.log but when i'm trying setState({...this.state,divisions:responseJson.division}) i'm not getting any data on console.
state
this.state={
token: data.token,
role: data.role,
userId: data.userId,
organizationId: data.organizationId,
organizationName: data.organization_name,
workspacePP: false,
workspaces: [],
divisions:[],
addWorkspace: null,
isDivisionViewable:false,
divisionName:null
};
function addDivision
addDivision=()=> {
const uri = `${APPURL}/workspace/division/create`;
console.log('dddddd',this.state)
fetch(uri, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.state.token}`
},
body: JSON.stringify({
workspace_id: this.state.workspaces[0].workspace_id,
organization_id: this.state.organizationId,
division:this.state.divisionName
}),
}).then((res)=>res.json()).then(responseJson=>{
if(!responseJson.status){
message.error(responseJson.error);
return;
}
console.log('dddd',responseJson);
this.setState({...this.state,divisions:responseJson.division})
})
console.log(this.state)//returns empty array
}
responseJson
{status: true, division: Array(1), created_at: {…}, user: {…}}
created_at:
updated_at: ["2019-03-09 14:05:26"]
__proto__: Object
division: Array(1)
0: {id: 5, userid: "t863060h", workspace_id: "ROPHV6W", workspace_name:
"workspace", created_at: "2019-03-09 13:39:31", …}
length: 1
__proto__: Array(0)
status: true
user:
created_at: "2019-03-08 18:29:56"
email: "trycatchh#mail.com"
email_verification: 1
id: 1
loginStatus: 0
mobile_otp: 0
mobile_verification: 0
phone: "9632587410"
role: "Admin"
slug: ""
status: 2
team: null
uid: null
updated_at: "2019-03-08 18:29:56"
userid: "t863060h"
username: "tryy catchh"
console.log(this.state)
nName: "tryCatchh", …}
addWorkspace: true
divisionName: "dud"
**divisions**: Array(0)//no data
length: 0
__proto__: Array(0)
isDivisionViewable: true
organizationId: "finalids"
organizationName: "tryCatchh"
role: "Admin"
userId: "t863060h"
workspacePP: false
workspaces: [{…}]
other funtction
showDivision=()=>{
console.log('dddd',this.state.divisions);
}
SetState is asynchronous so To see updated state value you need to
Change
this.setState({...this.state,divisions:responseJson.division})
To
this.setState({
divisions:responseJson.division
}, () => {
console.log(this.state.divisions);//here you will get updated divisions state value
});
Notice your setState is in then function, and will run after the API call response. Your console.log(this.state) will run immediately after calling the API.
if you want to see the final state after the API call, pass a callback func as the second parameter to setState like this:
this.setState({ divisions:responseJson.division }, () => console.log(this.state))
note: you don't need to destructure the state when calling setState, React does it for you already.

Cant set headers after they are sent ALSO CASTError: Cast to [ObjectId] failed

I seem to be getting 2 errors.....
Here is the Route:
router.post("/event", isLoggedIn, function (req,res){
// get data from form and add to events array
var title = req.body.title;
var date = req.body.date;
var description = req.body.description;
var venue = req.body.venue;
var photo = req.body.photo;
var category = req.body.category;
//get user data to save to the event.
var owner = {
id: req.user._id,
username: req.user.username
};
var newEvent = {category: category, title: title, date: date, description: description, venue: venue, photos:{link: photo,date: date}, owner: owner};
//Create the event itself in the database, event will return the actual database event.
Event.create(newEvent, function(err, event){
if (err) {
console.log(err)
} else {
//This takes the event owner ID and saves it into the Event model
console.log(event);
event.owner.id = req.user._id;
//This takes the event username and saves it into the Event model
event.owner.username = req.user.username;
event.save();
//Save the event ID in the user document
console.log(event);
User.findByIdAndUpdate(
req.user._id,
{$push: {events:{"ObjectId": event._id}}},
{save: true, upsert: true, new: true},
function (err,newEventData){
if(err){
console.log("error at saving the id ..." + err)
res.redirect("/dashboard");
} else {
console.log(newEventData);
}
}
);
//Add the Event ID to the User model
console.log (owner);
};
});
res.redirect('events');
});
Here is the output of the console.log of the returned value from Mongoose and also the error.
The id of the user 583f30b1e5e7e376502762f5
Below are all the events pulled{ _id: 583f30b1e5e7e376502762f5,
username: 'asdf',
__v: 0,
favoriteMoments: [],
favoriteEvents: [],
likeEvents: [],
likeMoments: [],
friends: [],
moments: [],
events: [],
categories: [] }
{ __v: 0,
title: 'asdf',
description: 'asdf',
_id: 583f3175b6a3b376a515c146,
comments: [],
photos: { link: '', date: null },
moments: [],
category: [ '' ],
owner: { id: 583f30b1e5e7e376502762f5, username: 'asdf' } }
{ __v: 0,
title: 'asdf',
description: 'asdf',
_id: 583f3175b6a3b376a515c146,
comments: [],
photos: { link: '', date: null },
moments: [],
category: [ '' ],
owner: { id: 583f30b1e5e7e376502762f5, username: 'asdf' } }
{ id: 583f30b1e5e7e376502762f5, username: 'asdf' }
error at saving the idCastError: Cast to [ObjectId] failed for value "[{"ObjectId":"583f3175b6a3b376a515c146"}]" at path "events"
events.js:141
throw er; // Unhandled 'error' event
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)
at ServerResponse.header (/var/www/familysite.com/node_modules/express/lib/response.js:719:10)
at ServerResponse.location (/var/www/familysite.com/node_modules/express/lib/response.js:836:15)
at ServerResponse.redirect (/var/www/familysite.com/node_modules/express/lib/response.js:874:18)
at /var/www/familysite.com/routes/eventRoute.js:67:29
at /var/www/familysite.com/node_modules/mongoose/lib/model.js:3388:16
at /var/www/familysite.com/node_modules/mongoose/lib/model.js:3388:16
at /var/www/familysite.com/node_modules/kareem/index.js:207:48
at /var/www/familysite.com/node_modules/kareem/index.js:127:16
at nextTickCallbackWith0Args (node.js:419:9)
at process._tickCallback (node.js:348:13)
Here is the schema of the Users Model:
const userSchema = new mongoose.Schema({
username: String,
password: String,
nickname: String,
firstName: String,
middleName: String,
lastName: String,
address: String,
city: String,
state: String,
phone: Number,
birthday: Date,
birthplace: String,
userCover: String,
categories: Array,
events: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Event"
}],
moments: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Moments"
}],
friends: [{
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}],
likeMoments: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Moments"
}],
likeEvents: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Event"
}],
favoriteEvents: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Event"
}],
favoriteMoments: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Moments"
}]
})
I have been getting no where with this Cast issue and now I have 2 errors which seems odd... getting very frustrated at this point and unsure where to go.
In the end, I have route that needs to create an event, save it event ID to the user that created it and then go to the /event page and display the data for each event.
If you look at the first block of code about 3/4 the way down...
this line:
{$push: {events:{"ObjectId": event._id}}},
Should look like this:
{$push: {events:{_id: event._id}}},
Thats it! so _id is how you tell it to be an ID.

Backbone Model Save: sending fields as "model" subobject

User Model
define(
[
'backbone'
],
function (Backbone) {
return Backbone.Model.extend({
url: '/proxy.php/users.json',
defaults: {
'first_name': '',
'last_name': '',
'work_email': ''
},
validation: {
first_name: {
required: true,
msg: 'Please enter a first name'
},
last_name: {
required: true,
msg: 'Please enter a last name'
},
work_email: {
required: true,
msg: 'Please enter a valid email'
}
}
});
}
);
View save data
onSave: function (ev) {
ev.preventDefault()
var details = $('.edit-user-form').serializeObject()
var object = new User()
return object.save(details, {
success: function (response) {
console.log(response, 'response')
}
})
},
details =
{first_name: "", last_name: "", birthdate: "", job_title: "", job_start_date: ""…}
birthdate: ""
first_name: ""
job_probation_ends: ""
job_start_date: ""
job_title: ""
last_name: ""
personal_address: ""
personal_email: ""
personal_phone_number: ""
work_address: ""
work_email: ""
work_phone_number: ""
The problem, the request sent by Backbone sends Form Data as:
model:{"first_name":"","last_name":"","work_email":"","birthdate":"","job_title":"","job_start_date":"","job_probation_ends":"","work_address":"","work_phone_number":"","personal_email":"","personal_address":"","personal_phone_number":""}
Why is it making the attributes a sub object of model? I would like the attributes sent as the root.
If you want to modify the structure of the data you send to the server, then override the toJSON method for your model:
toJSON: function () {
return { // structure the model as you wish here };
}

Categories

Resources