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?

  • \$\begingroup\$ I personally don't know, how to do it better. Maybe you can rethink your problem? Is there a way for you to have a single collection of widgets only, or components only, which already has this mapping preset correctly? Side note: I don't think hasOwnProperty is needed in this particular case. \$\endgroup\$ – Igor Soloydenko Oct 23 '17 at 8:15
  • \$\begingroup\$ The reason I am using hasOwnProperty is so that this.components which is a context object of a React class doesn't end up looking through its prototype chain, which might slow the whole thing down. Do you still think its not required? \$\endgroup\$ – Zaid Humayun Oct 24 '17 at 14:59

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\$ – Zaid Humayun Oct 23 '17 at 15:40
  • \$\begingroup\$ No, reduce doesn't have significant runtime improvement than for...of loop. It is just more functional flavor. Comparing with your implementing, the only improvement is to get rid of hasOwnProperty check. But as the first comment mentioned, hasOwnProperty may not be needed in this case. \$\endgroup\$ – Alex.S Oct 23 '17 at 17:55
  • 1
    \$\begingroup\$ That does not work, you should be assigning to widgetsObjkeys not its values. Should be Object.keys(widgetsObj).reduce((obj, key) => (obj[key] = components[widgetsObj[key]], obj), {}); \$\endgroup\$ – Blindman67 Oct 24 '17 at 5:22
  • \$\begingroup\$ Thanks for pointing out @Blindman67. I have updated the answer. \$\endgroup\$ – Alex.S Oct 24 '17 at 13:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.