I am usually constructing objects that do have fields in them or do not have them based on a condition so
let data
if(something === true) {
data = {
name: 'String',
something: 'Something'
}
else {
data = {
name: 'String'
}
}
but this seems like a very "dirty way to do this" as data needs to be redefined every time + if there were more if conditions this would become quiet big chunk of code. Is there a more concise way to achieve this?
Just conditionally add properties to the object - you don't need to define the whole thing in one go as an object literal.
let data = {
name: 'String'
};
if (something) {
data.something = 'Something';
}
you can use can a ternary operator like this:
let data = {
name: 'String',
something: (something) ? "Something" : undefined,
}
practically this should work because undefined
is what you get when trying to access a non-existing object property,
but keep in mind you're adding an enumerable property to the object.
You can use Object.assign
as follows, because it ignores non-object parameters:
let data let something = true data = Object.assign( { name: 'String' }, something && {something: 'Something'} ) console.log(data)
Or, if you prefer
something ? {something: 'Something'} : {}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.