I have a Javascript object otherObj and I construct myObj dynamically based on non-undefined values of otherObj. As of now, I manually compare and assign as below. But was wondering if there can be a more efficient way…Also not sure if it is possible to make it even more dynamic i.e. say if attr3 gets added in future, that also gets considered automatically.
let myObj = {};
if (otherObj.attr1 !== undefined) {
myObj['attr1'] = otherObj.attr1;
}
if (otherObj.attr2 !== undefined) {
myObj['attr2'] = otherObj.attr2;
}
2
Answers
You can try using for…in to iterate over the properties of
otherObj
and conditionally assign them tomyObj
:You can use the Nullish coalescing operator
Be careful if the otherObj[attr] is an object. You will need to clone it if you do not want subsequent actions on myObj to affect otherObj