簡體   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