0

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)])

2
  • 1
    do you want to keep the same object? Commented Sep 15, 2020 at 17:52
  • Console.log({ ...obj1, ...obj2 }) ? Commented Sep 15, 2020 at 17:52

1 Answer 1

5

You can use the spread operator for this:

const expected_output = {
  ...date_dict,
  ...data_dict
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.