# Mapping key value pairs between two JavaScript objects

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?

• 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. Oct 23, 2017 at 8:15
• 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? Oct 24, 2017 at 14:59

It might be a little cleaner to use .reduce instead of for...of... loop:
Object.keys(widgetsObj).reduce( (obj, key) => {

• 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. Oct 23, 2017 at 17:55
• 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), {}); Oct 24, 2017 at 5:22