In the following code I want to return all the same keys and values except the property color. If the name is default, return the color: '#1F2532'
, if it's different than default, it will call a function that gives me random colors color: pickColor([])
. But I think there is a better way to write this instead of repeating code and just changing the property color. How can I do this?
class Project {
static createProject(data) {
if (data.name !== 'default') {
return {
owner: {
name: data.owner,
avatar: data.ownerAvatar
},
users: [
{
name: data.owner,
avatar: data.ownerAvatar,
active: true,
}],
name: data.name,
retrospectives: [],
color: pickColor([])
}
} else {
return {
owner: {
name: data.owner,
avatar: data.ownerAvatar
},
users: [
{
name: data.owner,
avatar: data.ownerAvatar,
active: true,
}],
name: data.name,
retrospectives: [],
color: '#1F2532'
}
}
}
}
2 Answers 2
As said in a comment above, using a conditional assignment would be your best bet:
class Project {
static createProject(data) {
return {
owner: {
name: data.owner,
avatar: data.ownerAvatar
},
users: [
{
name: data.owner,
avatar: data.ownerAvatar,
active: true,
}],
name: data.name,
retrospectives: [],
color: data.name === 'default' ? '#1F2532' : pickColor([])
}
}
}
I am not familiar with javascript, so please excuse me if I get some semantics wrong. The simple answer is to change the position of "if
".
class Project {
static createProject(data) {
return {
owner: {
name: data.owner,
avatar: data.ownerAvatar
},
users: [
{
name: data.owner,
avatar: data.ownerAvatar,
active: true,
}],
name: data.name,
retrospectives: [],
if (data.name !== 'default') {
color: pickColor([])
} else {
color: '#1F2532'
}
}
}
}
An alternative to
if (data.name !== 'default') {
color: pickColor([])
} else {
color: '#1F2532'
}
is
colour: (data.name == 'default' ? '#1F2532' : pickColor([]))
p.s. haven't counted the brackets either, but you get the drift.
-
1\$\begingroup\$ You can't put an if-statement into an object literal. A conditional expression however should work fine. \$\endgroup\$le_m– le_m2018年01月22日 20:17:20 +00:00Commented Jan 22, 2018 at 20:17