繁体   English   中英

有条件地更新javascript对象

[英]Update javascript object conditionally

在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"
            ]
          }
        ]
      }
}     

想要检查是否有更好的方法来实现此目的,因为这是重复的代码,并且随着条件的增加,此方法将不再可维护。

您可以通过以下方式删除对象的属性:

delete myObj.routes;

要么

delete myObj['routes'];

那是您要找的东西吗?

请尝试以下操作:

myObj = {
        "option": ["valid"],
        "cities": [
          "London",
          "Paris",
          "Rome"
        ],
        "def": [
          {
            "name": "name1",
            "attributes": [
              "test"
            ]
          }
        ]
      }

if(somecondition) {
   myObj.routes = [{
          "section": 'option1',
          "class": true
        }]
}   

之前定义对象,然后根据条件添加routes

您可以尝试以下代码。 如果不满足条件,则可以从对象中删除路由。 希望对您有所帮助!

 myObj = {
            "option": ["valid"],
            "cities": [
              "London",
              "Paris",
              "Rome"
            ],
            "routes": [{
              "section": 'option1',
              "class": true
            }],
            "def": [
              {
                "name": "name1",
                "attributes": [
                  "test"
                ]
              }
            ]
          };

        if(!somecondition) {
          delete myObj.routes;
        }

通过稍后根据您的条件简单地添加routes属性

myObj = {
  "option": ["valid"],
  "cities": [
    "London",
    "Paris",
    "Rome"
  ],
  "def": [{
    "name": "name1",
    "attributes": [
      "test"
    ]
  }]
};

if(somecondition) {
   myObj.routes = [{
       "section": 'option1',
       "class": true
   }];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM