Reputation: 35
I have 2 js objects:
var date_dict = {2017_M1: 0, 2017_M10: 0, 2017_M11: 0}
var data_dict = {2017_M1: 10, 2017_M11: 50}
Expected output = {2017_M1: 10, 2017_M10: 0, 2017_M11: 50}
Aim: To map the values of data_dict (target) to date_dict (source) where they exist. Keep all keys of date_dict (source). Keep values of date_dict if not exist in data_dict.
There will never be any keys in data_dict that do not exist in date_dict (this is universe of dates).
I've tried, based on switching key/value an answer to How to replace object key with matching key value from another object
Below attempt just returns the date_dict, it doesn't get the data_dict values.
Thanks :
var expected_output = Object.fromEntries(
Object.entries(date_dict).map(([k,v]) => [ k, (data_dict[v] || v)])
Upvotes: 0
Views: 412
Reputation: 78910
You can use the spread operator for this:
const expected_output = {
...date_dict,
...data_dict
};
Upvotes: 5