我需要将某个对象的所有属性设置为null
。
但是这个对象可能非常大,所以我不能一个一个地处理。
如何一次性地设置所有属性?
我需要将某个对象的所有属性设置为null
。
但是这个对象可能非常大,所以我不能一个一个地处理。
如何一次性地设置所有属性?
这里有一个有用的函数叫做 'Object.keys()',它会返回一个对象所有属性的名称。
let setAll = (obj, val) => Object.keys(obj).forEach(k => obj[k] = val);
let setNull = obj => setAll(obj, null);
非箭头函数版本:
function setAll(obj, val) {
/* Duplicated with @Maksim Kalmykov
for(index in obj) if(obj.hasOwnProperty(index))
obj[index] = val;
*/
Object.keys(obj).forEach(function(index) {
obj[index] = val
});
}
function setNull(obj) {
setAll(obj, null);
}
Object.keys
的参考文献。同时,请使用正确的术语,"Attributes"是不正确的。最后,如果你要全面运用函数式编程,应该将函数定义为setAll = val => obj =>...
,然后使用const setNull = setAll(null);
吗? - user663031Object.keys(obj).forEach((i) => obj[i] = null);
使用Array.reduce
的另一种方法。它不会覆盖现有对象。这仅适用于对象只有简单值的情况。
const newObj = Object.keys(originalObj).reduce(
(accumulator, current) => {
accumulator[current] = null;
return accumulator
}, {});
Object.keys()
,或者使用for in
,如下所示:for (key in obj) {
if (obj.hasOwnProperty(key)) {
obj[key] = null;
}
}
但在这种情况下,您需要检查hasOwnProperty()
。
hasOwnProperty
时,ESLint会抛出一个no-prototype-builtins
错误。可以使用Object.prototype.hasOwnProperty.call(obj, key)
来代替以消除这个错误。 - Sam Finniganfunction setEmpty(input){
let keys = Object.keys(input);
for( let key of keys ){
if(typeof input[key] != "object" ){
input[key] = null;
}else{
setEmpty(input[key]);
}
}
return input;
}
使用 cloneDeepWith
,Lodash 可以管理此问题。
我对相同问题的解决方案:
import * as _ from 'lodash';
const bigObj = {"big": true, "deep": {"nested": {"levels": "many" } } };
const blankObj = _.cloneDeepWith(bigObj, (value) => {return _.isObject(value) ? undefined : null});
console.log(blankObj);
// outputs { big: null, deep: { nested: { levels: null } } }
在自定义器中返回undefined
对我来说并不明显,但是这篇答案解释说这样做会触发递归。
您可以像这样使用Object.fromEntries和Object.entries
Object.fromEntries(
Object.keys(obj).map((key) => [key, null])
)
export const setObjToNull = (obj) => {
var returnObj = {};
Object.keys(obj).map((key) => {
let nullObj = { [key]: '' };
Object.assign(returnObj, nullObj);
})
return returnObj;
}
你可以使用for in
。以下是一个例子:
let obj = {prob1:"value1", prob2:"value2"}
for(let prob in obj){obj[prob]=null}