\$\begingroup\$
\$\endgroup\$
2
I have two JavaScript objects:
const widgetsObj = {
inputWidget: "MyInputWidget",
checkboxWidget: "MyCheckboxWidget",
geoWidget: "MyGeoWidget"
};
this.components = {
"MyInputWidget": MyInputWidget,
"MyCheckboxWidget": MyCheckboxWidget,
"MyGeoWidget": MyGeoWidget
};
The end goal is to map all keys from widgetsObj
to all values from this.components
. The end object should look like this.
let endObj = {
inputWidget: MyInputWidget,
checkboxWidget: MyCheckboxWidget,
geoWidget: MyGeoWidget
}
Right now, I am doing this like so
let returnObj = {};
for(const key of Object.keys(widgets)) {
if(this.components.hasOwnProperty(widgets[key])) {
returnObj[key] = this.components[widgets[key]];
}
}
return returnObj;
where widgets
represents widgetsObj
.
Is there a better way to do this rather than look for each value by mapping through the whole object repeatedly?
asked Oct 23, 2017 at 7:11
1 Answer 1
\$\begingroup\$
\$\endgroup\$
4
It might be a little cleaner to use .reduce
instead of for...of...
loop:
Object.keys(widgetsObj).reduce( (obj, key) => {
obj[key] = this.components[widgetsObj[key]];
return obj;
}, {});
-
\$\begingroup\$ This definitely looks a lot cleaner. However, is there any runtime improvement that you are aware of by using either of those options? \$\endgroup\$redixhumayun– redixhumayun2017年10月23日 15:40:34 +00:00Commented Oct 23, 2017 at 15:40
-
\$\begingroup\$ No,
reduce
doesn't have significant runtime improvement thanfor...of
loop. It is just more functional flavor. Comparing with your implementing, the only improvement is to get rid ofhasOwnProperty
check. But as the first comment mentioned,hasOwnProperty
may not be needed in this case. \$\endgroup\$Alex.S– Alex.S2017年10月23日 17:55:17 +00:00Commented Oct 23, 2017 at 17:55 -
1\$\begingroup\$ That does not work, you should be assigning to
widgetsObj
keys not its values. Should beObject.keys(widgetsObj).reduce((obj, key) => (obj[key] = components[widgetsObj[key]], obj), {});
\$\endgroup\$Blindman67– Blindman672017年10月24日 05:22:23 +00:00Commented Oct 24, 2017 at 5:22 -
\$\begingroup\$ Thanks for pointing out @Blindman67. I have updated the answer. \$\endgroup\$Alex.S– Alex.S2017年10月24日 13:54:55 +00:00Commented Oct 24, 2017 at 13:54
lang-js
hasOwnProperty
is needed in this particular case. \$\endgroup\$