我有以下对象:
obj = {"foo":"bar", "foo2":"bar2", "foo3":"bar3"};
我一直在尝试几次迭代,但是无法捕捉到值(bar,bar2,bar3),只能找到键。
我需要做的是清除这些值,因此键恰好都是空的。
我尝试了以下内容:
$.each( obj, function( key, value ) {
delete value;
// or also: value = '';
});
还有类似的东西:
$(obj).each(function (key,value) -- //same content as last one.
Object.values(obj).forEach(function (key) {
var value = obj[key];
});
答案 0 :(得分:1)
遍历该对象并将值设置为null
/ undefined
或任何您想要的空值。
var obj = {"foo":"bar", "foo2":"bar2", "foo3":"bar3"};
Object.keys(obj).forEach(k => { obj[k] = null; })
console.log(obj);

或者,如果您要删除密钥,请使用delete
:
var obj = {"foo":"bar", "foo2":"bar2", "foo3":"bar3"};
Object.keys(obj).forEach(k => { delete obj[k]; })
console.log(obj);

答案 1 :(得分:1)
您可以通过循环执行此操作:
var test = {"a":"abc", "b":"ref", "c": "def"}
console.log("Before:");
console.log(test);
for (var key in test) {
test[key] = "";
}
console.log("After:");
console.log(test);
答案 2 :(得分:0)
var obj = {"foo":"bar", "foo2":"bar2", "foo3":"bar3"};
for(let key of Object.keys(obj)){
obj[key]=""; //empty
}
console.log(obj);