在我的 Angular 组件中,我定义了一个 Javascript 对象,例如
myObj = {
"option": ["valid"],
"cities": [
"London",
"Paris",
"Rome"
],
"routes": [{
"section": 'option1',
"class": true
}],
"def": [
{
"name": "name1",
"attributes": [
"test"
]
}
]
}
现在,根据条件,我想包含或排除“路线”部分。
所以,目前我正在这样做
if(somecondition) {
myObj = {
"option": ["valid"],
"cities": [
"London",
"Paris",
"Rome"
],
"routes": [{
"section": 'option1',
"class": true
}],
"def": [
{
"name": "name1",
"attributes": [
"test"
]
}
]
}
} else {
myObj = {
"option": ["valid"],
"cities": [
"London",
"Paris",
"Rome"
],
"def": [
{
"name": "name1",
"attributes": [
"test"
]
}
]
}
}
想要检查是否有更好的方法来实现这一点,因为这是代码的重复,并且随着条件的增加,这将不再可维护。
最佳答案
请尝试以下操作:
myObj = {
"option": ["valid"],
"cities": [
"London",
"Paris",
"Rome"
],
"def": [
{
"name": "name1",
"attributes": [
"test"
]
}
]
}
if(somecondition) {
myObj.routes = [{
"section": 'option1',
"class": true
}]
}
先定义对象,然后根据条件添加路由
。
关于javascript - 有条件地更新 javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47029528/