JS中优化Object.assign:将undefined转为空字符串或忽略空属性
优化Object.assign处理空属性的优雅方案
嘿,这个场景我太熟悉了!你的需求其实可以通过两种更简洁的方式实现,分情况来看:
一、把undefined/null转为空字符串
如果只是想把空值统一转成空字符串,不需要额外声明变量,直接在解构或者属性赋值时处理就行:
方式1:解构时设置默认值
这种方式适合当attributes里没有对应的属性(或者属性值为undefined)时,直接给默认空字符串:
const { one = "", two = "", three = "" } = attributes; return Object.assign(props, { "data-one": one, "data-two": two, "data-three": three });
方式2:用空值合并运算符??处理null/undefined
如果属性可能被设置为null(不仅仅是undefined),用??更精准——它只会把null和undefined转为空字符串,不会影响0、false等合法值:
const { one, two, three } = attributes; return Object.assign(props, { "data-one": one ?? "", "data-two": two ?? "", "data-three": three ?? "" });
二、理想方案:不复制任何空属性
如果希望直接跳过值为null/undefined的属性,不往props里添加对应的data-*属性,可以用这两种方式:
方式1:条件扩展运算符(最简洁)
利用对象扩展运算符...的特性:当条件为false时,扩展的空对象会被忽略,不会添加到目标对象中:
const { one, two, three } = attributes; return Object.assign(props, { ...(one != null && { "data-one": one }), ...(two != null && { "data-two": two }), ...(three != null && { "data-three": three }) });
这里的!= null相当于同时判断null和undefined;如果要严格只过滤undefined,可以改成typeof one !== 'undefined'。
方式2:过滤对象键值对(适合属性较多的场景)
如果后续要处理的属性变多,这种方式更容易维护——先收集所有属性,过滤空值后再转成目标格式:
const { one, two, three } = attributes; // 先构建键值对,过滤空值后转成data-前缀的属性 const validDataAttrs = Object.fromEntries( Object.entries({ one, two, three }) .filter(([_, value]) => value != null) .map(([key, value]) => [`data-${key}`, value]) ); return Object.assign(props, validDataAttrs);
这样不管是转空字符串还是过滤空属性,代码都比你之前的写法简洁很多,也更符合现代JS的风格~
内容的提问来源于stack exchange,提问作者CyberJunkie
相关产品推荐
相关产品推荐

