Cyb*_*kie 2 javascript ecmascript-6
我正在使用Object.assign()将值复制到对象:
const { one, two, three } = attributes;
return Object.assign( props, {
"data-one": one,
"data-two": two,
"data-three": three
} );
Run Code Online (Sandbox Code Playgroud)
如果属性的值为空,则返回undefined.我希望它返回一个空字符串或理想情况下不复制任何空属性.
我试过这个:
const { one, two, three } = attributes;
var oneValue = one ? one : "";
var twoValue = two ? two : "";
var threeValue = three ? three : "";
return Object.assign( props, {
"data-one": oneValue,
"data-two": twoValue,
"data-three": threeValue
} );
Run Code Online (Sandbox Code Playgroud)
它的工作原理是发送空值而不是未定义,但似乎不是很花哨.有没有更好的方法来处理这个?
您可以在使用解构时定义默认值.
const attributes = { one: 'one' };
const { one = '', two = '', three = '' } = attributes;
const props = {}
console.log(Object.assign( props, {
"data-one": one,
"data-two": two,
"data-three": three
}));Run Code Online (Sandbox Code Playgroud)
最后,如果您有许多常见的行为,您可以只命名要复制的属性并编写循环.