jquery - Conditionally adding properties to JavaScript object -
is there more concise or readable way of doing this?
var foo={a:111,c:333, somepropertythatshouldntbeadded:'xxx'}; var myobj={x:1,y:2,z:3}; if(foo.a){myobj.a=foo.a;} if(foo.b){myobj.b=foo.b;} if(foo.c){myobj.c=foo.c;}
edit. context why doing below.
var obj={value:this.text,css:{color:'#929292',margin:'1px 0px'}}; if(this.width){obj.css.width=this.width;} if(this.type){obj.type=this.type;} if(this.id){obj.id=this.id;} var input=$('<input/>',obj)
you use simple loop-based approach:
var foo={a:111,c:333, somepropertythatshouldntbeadded:'xxx'}; var myobj={x:1,y:2,z:3}; ['a','b','c'].foreach(function(key) { if(key in foo) { myobj[key] = foo[key]; } });
notice how used in
keyword. current solution not work if value of property (e.g.) false
or 0
.
additionaly, better solutions, provide context: why conditionally copying properties? perhaps can avoid begin with.
Comments
Post a Comment