重置 Javascript 对象中所有值的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27529378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to reset all values in an Javascript object
提问by runtimeZero
My javascript object looks something like:
我的 javascript 对象看起来像:
$scope.display = {
current: {
key1: 'value1',
key2: ['a', 'b'],
key3: 'value2'
}
}
Upon some events in my code, I would like to reset these values to undefined like below:
在我的代码中发生某些事件时,我想将这些值重置为 undefined ,如下所示:
$scope.display = {
current: {
key1: undefined,
key2: [],
key3: undefined
}
}
I use libraries like lodash, however i don't see any function that would perform this. I know how to do this manually, but I was wondering if there is a "Best practices" way of performing this task.
我使用像 lodash 这样的库,但是我没有看到任何可以执行此操作的函数。我知道如何手动执行此操作,但我想知道是否有执行此任务的“最佳实践”方式。
采纳答案by dfsq
I would create a helper function returning object structure:
我会创建一个帮助函数返回对象结构:
function getDisplayObject() {
return {
current: {
key1: undefined, // or you can omit undefined keys
key2: [],
key3: undefined
}
};
}
$scope.display = getDisplayObject();
So later when you need to reset data you would execute $scope.display = getDisplayObject();again.
所以稍后当您需要重置数据时,您将$scope.display = getDisplayObject();再次执行。
回答by Yauheni Prakopchyk
Here is my solution with lodash mapValuesfunction:
这是我使用 lodashmapValues函数的解决方案:
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>
回答by George Abitbol
What about this?
那这个呢?
// 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)
回答by Adam Rackis
You would loop the properties of your object like this
你会像这样循环你的对象的属性
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
}
}
Array check subject to some potential problems described in the comments here
数组检查受此处评论中描述的一些潜在问题的影响
回答by Tristan Lee
In my Angular controller, I do the following:
在我的 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);
}
Initially the scope is empty, so I clone it, and whenever it needs reset, simply call a function. However, without knowing the scope of your project, it's hard to determine the best way to handle it.
最初范围是空的,所以我克隆它,每当它需要重置时,只需调用一个函数。但是,在不知道项目范围的情况下,很难确定处理它的最佳方式。
回答by Syed Nasir Abbas
I did it in AngularJS controller as:
我在 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();
}
In this way you do not keep a copy of empty or default object. So no extra cost.
通过这种方式,您不会保留空对象或默认对象的副本。所以没有额外的费用。
回答by Mendy
A good way to deal with this would be to use a class instead of an object literal, like:
处理这个问题的一个好方法是使用类而不是对象文字,例如:
class current {
constructor() {
this.key1 = undefined;
this.key2 = [];
this.key3 = undefined;
}
}
And whenever you want to clear all the values you can just create a new instance of this class, like:
每当您想清除所有值时,您只需创建此类的新实例,例如:
$scope.display.current = new current();
回答by He Huang
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);
}
}
};
回答by AndreaBogazzi
If you are using Jquery, like it seems you are doing, you can do that:
如果您正在使用 Jquery,就像您正在做的那样,您可以这样做:
Preapre an empty template of your object:
准备一个空的对象模板:
var emptyTemplate = {
current: {
key1: undefined,
key2: [],
key3: undefined
}
}
and then run:
然后运行:
$scope.display = $.extend(true, {}, emptyTemplate);
If you want to automate it, define some data binding:
如果你想自动化它,定义一些数据绑定:
var defaults = {
String: undefined,
Array: [],
bool: false
}
Then loop in your object, like other suggestions:
然后循环你的对象,就像其他建议一样:
function resetObj (obj) {
_(obj).forEach(
function(value, key, objRef) {
if (_.isObject(value)) {
resetObj(objRef[key]);
} else {
var myvarType = typeOf value;
objRef[key] = defaults[myvarType];
}
}
);
}
I copied this nesting function from other answer, just to add my two cents.
我从其他答案中复制了这个嵌套函数,只是为了增加我的两分钱。
回答by epascarello
There is no built in way. You would need to loop through and set the defaults based on type.
没有内置的方式。您需要遍历并根据类型设置默认值。
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>
Basic idea if you have nested objects
如果您有嵌套对象的基本想法
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>

