Update object array without adding new properties from another object - javascript

Is it possible to update only the existing property values of an object without adding new properties from another object?
Here is my example.
form = {name: '',email: ''};
data = {name: 'sample', email: 'sample#gmail.com', datofbirth: '6/2/1990' };
form = {...form, ...data};
console.log(form);
Result:
{"name":"sample","email":"sample#gmail.com","datofbirth":"6/2/1990"}
Expected Result:
{"name":"sample","email":"sample#gmail.com"}
I dont want the dateofbirth or any new property added on my form object.

Not sure this is what you want, hope it helps
const form = { name: '', email: '' };
const data = {
name: 'sample',
email: 'sample#gmail.com',
datofbirth: '6/2/1990',
};
Object.keys(form).forEach(key => {
if (data.hasOwnProperty(key)) {
form[key] = data[key];
}
});
console.log(form);

Only add the keys you want in the spread rather than the whole object
form = { ...form, name: data.name, email: data.email };

Iterate over all the keys in form and generate a new object using Object.assign and spread syntax.
const form = {name: '',email: ''},
data = {name: 'sample', email: 'sample#gmail.com', datofbirth: '6/2/1990' },
result = Object.assign(...Object.keys(form).map(k => ({[k] : data[k]})));
console.log(result);

Related

Change a value from a nested object using localstorage

I have this code that set the obj value in localstorage.
const obj = {
name: "Bill",
meta: {
age: 18
}
};
const data = localStorage.setItem('user', JSON.stringify(obj));
Now i want to change the age key in the localstorage:
localStorage.setItem('user', JSON.stringify({ ...data, ...data.meta.age= 15 } }));, but it does not work.
How to change the value above and to see the changes in localstorage?
Assuming you have data, the problem is that ...data.meta.age = 15 is a syntax error. You don't use = in object literals, and it does't make sense to try to spread the age property (which is a number). Instead:
const newData = {
...data,
meta: {
...data.meta,
age: 15,
},
};
localStorage.setItem("user", JSON.stringify(newData));
Notice how we have to create a new outermost object and also a new object for meta.
Live Example:
const data = {
name: "Bill",
meta: {
occupation: "Programmer", // Added so we see it get copied
age: 18,
},
};
const newData = {
...data,
meta: {
...data.meta,
age: 15,
},
};
console.log(newData);

Set correct value for each property in an object

I have a problem in pushing input into array. I have an array with some properties and I'm going to push some value into it, but I have no idea how to tell which value is for which property.
This is my array that I want to push into it:
validInput: [{
image: avatar1,
name: '',
email: '',
passwrod: '',
phone: '',
revenue: '',
create_date: '',
age: '',
id: ''
}]
This is my function that pushes into the array:
validation(value, REGEX) {
if (REGEX.test(value) === true) {
this.state.validInput.push(value);
this.setState({
validInput: this.state.validInput
});
} else {
console.log('error');
}
}
If I understood correctly and you wish to convert your object inside validInput array into an array of objects you can do this:
Let's say we are looking to get an array of objects with the following format:
{keyName:key,keyValue:value}
we can do something like that:
const newArray = new Array();
Object.keys(this.validInput[0])
.forEach(singleKey => {
newArray.push({
keyName:singleKey,
keyValue:this.validInput[0][singleKey]
})
})
// finally - we will have the newly formatted array in newArray
I think you should have some unique way of identifying the object you want for filtering process like id, name etc. For modified function,
validation(id, value, REGEX) {
if(REGEX.test(value)){
this.state.validInput.map((user) => {
if(user.id === id) {
user.PROPERTY_YOU_NEED_TO_UPDATE = value
}
}
}
}
Since this validInput might receive another object better use to identify it using if(user.id === id). If validInput won't receive another there is no point to use array of objects.
validInput: {
image: avatar1,
name: '',
email: '',
passwrod: '',
phone: '',
revenue: '',
create_date: '',
age: '',
id: ''
}
If it's like above you can just edit the property you want...
this.setState(state => {
let user = Object.assign({}, state.validInput);
user.PROPERTY_YOU_NEED_TO_UPDATE = value;
return { user };
})

Typescript - Conditional property of object

I have the following object to which I wish to have a conditional property:
{ name: this.username, DOB: new Date(this.inputDate)}
Say, I wish to add a third property called gender if the user has specified their gender. What would the proper syntax for the following be:
{ name: this.username, DOB: new Date(this.inputDate), if(this.userGender) gender: this.userGender}
P.S. I do not wish to have the gender property in my object if there is no value along with it. So how can I only create the property if the condition is satisfied?
Ideally, you would just add the appropriate property as a second action after declaring your object. So something like:
const myObj = {
name: this.username,
DOB: new Date(this.inputDate),
}
if(this.userGender) myObj.gender = this.userGender;
However, sometimes it's nice to declare an "optional" property inline with the rest of them, in which case you can use object spread to get the effect you're looking for:
const myObj = {
name: this.username,
DOB: new Date(this.inputDate),
...this.userGender
? { gender: this.userGender }
: {}
}
it can be done like this too, more clean and readable.
const myObj = {
name: this.username,
DOB: new Date(this.inputDate),
...(this.userGender && { gender : this.userGender })
}
Try this
let userObj = { name: this.username, DOB: new Date(this.inputDate) }
if(this.userGender)
userObj[:gender] = this.userGender;

spread operator form submission in express.js

Can spread operator solve below problem? Imagine I have more fields, then I have to declare req.body.something for every single fields, that's so tedious.
app.use((res,req,next) => {
const obj = {
name: req.body.name,
age: req.body.age,
gender: req.body.gender
}
//
User.saveUser(resp => res.json(resp)) //User model
})
You can use destructuring assignment:
const obj = req.body;
const { name, age, gender } = obj;
But, still you will have to validate it, and count all of them in your scheme.
Update:
Adding some validation example.
Assuming such schema in your route:
const tv4 = require('tv4');
const schema = {
type: 'object',
properties: {
name: 'string',
age: number,
gender: {
type: 'string',
pattern: /f|m/i
}
},
required: ['name']
};
And then, in your handler you validate:
if (tv4.validate(req.body, schema) {
// continue your logic here
} else {
// return 400 status here
}
You can use lodash's pick():
_.pick(object, [paths])
Creates an object composed of the picked object properties.
Example code is:
const _ = require('lodash');
...
const obj = _.pick(req.body, ['name', 'age', 'gender']);
If gender does not exist in req.body, it would be ignored -- the result obj object won't have a gender field.
If all the req.body fields are needed, you can just assign req.body to obj:
const obj = req.body;
To validate req.body content, you can use lodash's .has():
_.has(object, path)
Checks if path is a direct property of object.
Example code would be:
_.has(req.body, ['name', 'age', 'gender']); // return true if all fields exist.
You can use destructuring assignment
const { name, age, gender } = req.body
or if you wanna use spread operation, you can use :
const obj = { ...req.body }
Hope it helps!

Check if property is not undefined

I'm building a node+express app and I'm filling an object with JSON that's submitted from a form in the frontend. This works, unless I leave a field empty in the form so that e.g. req.body.address.street is empty/undefined.
This will result in the error:
TypeError: Cannot read property 'street' of undefined
var b = new Business({
name: req.body.name,
phone: req.body.phone,
address: {
street: req.body.address.street,
postalCode: req.body.address.postalCode,
city: req.body.address.city
},
owner: {
email: req.body.owner.email,
password: req.body.owner.password
}
});
My question is how I can best prevent my app from crashing when values are empty. I would like to avoid manually checking each and every property in my app against undefined.
I'm wondering what the best practice is for this common issue.
I don't know if you use jQuery in your project, but if you do, you can create a mask:
// creating your object mask
var req = {
body: {
name: '',
phone: '',
address: {
street: '',
postalCode: '',
city: ''
},
owner: {
email: '',
password: ''
}
}
}
And then, you simply use the jQuery "extend" method (req2 is your submmited object):
$.extend(true, req, req2);
I've create this fiddle for you!
-
Update
Nothing related to your question, but I've just noticed that you're passing an object with a similar structure of req.body to the Business class. However, there is no need to copy property by property manually - you can make, for example, a simple copy of req.body to pass as parameter:
var b = new Business($.extend({}, req.body));
or
var b = new Business(JSON.parse(JSON.stringify(req.body)));
You can't, really. You have two options;
Use a try/ catch:
try {
var b = new Business({
//
});
} catch (e) {
// Something wasn't provided.
}
... or you can define a helper function:
function get(path, obj) {
path = path.split('.');
path.shift(); // Remove "req".
while (path.length && obj.hasOwnProperty(path[0])) {
obj = obj[path.shift()];
}
return !path.length ? obj : null;
}
... you could then replace your use of req.body.address.street etc. with get('req.body.address.street', req).
See a demo here; http://jsfiddle.net/W8YaB/

Categories