有条件地更新javascript对象

时间:2017-10-31 06:57:57

标签: javascript angular

在我的Angular组件中,我正在定义一个Javascript对象,例如

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

现在根据条件,我想要包含或排除'routes'部分。

所以,目前我正在这样做

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

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

4 个答案:

答案 0 :(得分:1)

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

delete myObj.routes;

delete myObj['routes'];

这就是你要找的东西吗?

答案 1 :(得分:1)

请尝试以下方法:

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

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

在之前定义对象,并根据条件添加routes

答案 2 :(得分:0)

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

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

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

答案 3 :(得分:0)

稍后根据您的条件添加routes属性

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

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