重置Javascript对象中所有值的最佳方法

时间:2014-12-17 15:44:41

标签: javascript lodash

我的javascript对象看起来像:

$scope.display = {
  current: {
       key1: 'value1',
       key2: ['a', 'b'],
       key3: 'value2'
    }
}

在我的代码中发生一些事件后,我想将这些值重置为未定义,如下所示:

$scope.display = {
  current: {
       key1: undefined,
       key2: [],
       key3: undefined
    }
}

我使用像lodash这样的库,但是我没有看到任何可以执行此操作的函数。 我知道如何手动执行此操作,但我想知道是否有“最佳实践”方法来执行此任务。

11 个答案:

答案 0 :(得分:5)

我会创建一个返回对象结构的辅助函数:

function getDisplayObject() {
    return {
        current: {
            key1: undefined, // or you can omit undefined keys
            key2: [],
            key3: undefined
        }
    };
}

$scope.display = getDisplayObject();

所以稍后当你需要重置数据时,你会再次执行$scope.display = getDisplayObject();

答案 1 :(得分:3)

以下是我使用lodash mapValues函数的解决方案:



var $clearObject = function(value) {
  if (_.isString(value)) {
    return undefined
  };
  if (_.isArray(value)) {
    return [];
  };
};

var $scopeDisplay = {
  current: {
    key1: 'value1',
    key2: ['a', 'b'],
    key3: 'value2'
  }
};

$scopeDisplay.current = _.mapValues($scopeDisplay.current, $clearObject);

console.log($scopeDisplay);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js"></script>
&#13;
&#13;
&#13;

答案 2 :(得分:2)

您可以像这样循环对象的属性

for (var key in current){
    if (current.hasOwnProperty(key)){
        if (typeof current[key] === 'string'){
            current[key] = undefined;
        } else if (current[key] instanceof Array) {
            current[key] = [];
        } // else ???  Not sure how you want to handle other types
    }
}

数组检查可能会受到评论here

中描述的一些潜在问题的影响

答案 3 :(得分:1)

在我的Angular控制器中,我执行以下操作:

    $scope.user = {
        firstname: "",
        lastname: "",
        displayname: "",
        email: "",
        password: "",
        passwordConfirm: ""
    };

    // default state of the form
    $scope.default = angular.copy($scope.user);

    /**
     * Resets the form to its default state
     * @return {void}
     */
    $scope.reset = function () {
        $scope.user = angular.copy($scope.default);
    }

最初范围是空的,所以我克隆它,只要它需要重置,只需调用一个函数。但是,如果不知道项目的范围,很难确定处理它的最佳方法。

答案 4 :(得分:1)

我在AngularJS控制器中做到了:

function item_object() {
    var list_item = {
        ID: '',
        Title: '',
        LastName: '',
        Contact: '',
        City: ''
    };

  return list_item;
}

//Define the object for the item
$scope.Item = item_object();

// Reset product details
$scope.clear = function () {
    $scope.Item = item_object();
}

这样您就不会保留空对象或默认对象的副本。所以没有额外的费用。

答案 5 :(得分:1)

这个怎么样?

// If you just want to reset a simple object
let reset = (obj) => {
  Object.keys(obj).map(key => {
    if (obj[key] instanceof Array) obj[key] = []
    else obj[key] = undefined
  })
}


// If you want to reset a complex object
let recursiveReset = (obj) => {
  Object.keys(obj).map(key => {
    // Test if it's an Object
    if (obj[key] === Object(obj[key])) {
      recursiveReset(obj[key])
      return
    }
    if (obj[key] instanceof Array) obj[key] = []
    else obj[key] = undefined
  })
}

// So you can simply use
reset($scope.display.current)
// or
recursiveReset($scope.display)

test link

答案 6 :(得分:0)

如果你正在使用Jquery,就像你正在做的那样,你可以这样做:

预先填充对象的空模板:

var emptyTemplate = {
  current: {
       key1: undefined,
       key2: [],
       key3: undefined
    }
}

然后运行:

 $scope.display = $.extend(true, {}, emptyTemplate);

如果要自动化它,请定义一些数据绑定:

var defaults = {
 String:  undefined,
 Array: [],
 bool: false
}

然后在你的对象中循环,就像其他建议一样:

function resetObj (obj) {
    _(obj).forEach(
        function(value, key, objRef) {
            if (_.isObject(value)) {
                resetObj(objRef[key]);
            } else {                    
              var myvarType = typeOf value;
              objRef[key] = defaults[myvarType];
            }
        }
    );
}  

我从其他答案复制了这个嵌套函数,只是为了加上我的两分钱。

答案 7 :(得分:0)

没有内置方式。您需要循环并根据类型设置默认值。

var x = {
    current: {
        key1: 'value1',
        key2: ['a', 'b'],
        key3: 'value2'
    }
};

_(x.current).forEach(
    function(value, key, obj) {
        var result = undefined;
        if (_.isArray(value)) {
            result = [];
        }
        obj[key] = result;
    }
);

console.log(x);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>

如果你有嵌套对象的基本想法

var x = {
        current: {
            key1: 'value1',
            key2: ['a', 'b'],
            key3: 'value2',
            xxxx:  {
                keyx1: 'valuex1',
                keyx2: ['xa', 'xb'],
                keyx3: 'valuex2'
            }         
        }
    };

function resetObj (obj) {
    _(obj).forEach(
        function(value, key, objRef) {
            var result = undefined;
            if (_.isObject(value)) {
                resetObj(objRef[key]);
            } else {                    
              if (_.isArray(value)) {
                  result = [];
              }
              objRef[key] = result;
            }
        }
    );

}  

resetObj(x)
console.log(x);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>

答案 8 :(得分:0)

一种解决此问题的好方法是使用类而不是对象文字,例如:

class current {
    constructor() {
        this.key1 = undefined;
        this.key2 = [];
        this.key3 = undefined;
    }
}

只要您想清除所有值,就可以创建此类的新实例,例如:

$scope.display.current = new current();

答案 9 :(得分:0)

function isObject (value) {
  return value && typeof value === 'object' && value.constructor === Object;
}

const resetObj = (obj, resetVal) => {
  if(!isObject(obj)) return;
  for(let i in obj){
    if(!obj.hasOwnProperty(i)) continue;
    if(!isObject(obj[i])){
      obj[i] = resetVal;
    }else{
      resetObj(obj[i], resetVal);
    }
  }
};

答案 10 :(得分:0)

++++++++++++++++++++++++++打字稿解决方案++++++++++++++++++++++++++++

 private deviceSettingsToReset: RemoteDeviceSetting;
    
    // depp copy of response into deviceSettingsToReset variable which need to use in reset functionality in UI.
    this.deviceSettingsToReset = JSON.parse(JSON.stringify(response));
    
    // assign value from original copy.
    this.selectedAlgorithm = JSON.parse(JSON.stringify(this.deviceSettingsToReset));