[英]Javascript: How to replace first object's values with values from second object, if objects have matching keys
I have 2 js objects:我有 2 个 js 对象:
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}
预期产出 =
{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.目标:将 data_dict(目标)的值映射到它们存在的 date_dict(源)。 Keep all keys of date_dict (source).
保留 date_dict 的所有键(来源)。 Keep values of date_dict if not exist in data_dict.
如果 data_dict 中不存在,则保留 date_dict 的值。
There will never be any keys in data_dict that do not exist in date_dict (this is universe of dates). data_dict 中永远不会有 date_dict 中不存在的任何键(这是日期范围)。
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.下面的尝试只返回 date_dict,它没有得到 data_dict 值。
Thanks :谢谢 :
var expected_output = Object.fromEntries(
Object.entries(date_dict).map(([k,v]) => [ k, (data_dict[v] || v)])
You can use the spread operator for this:您可以为此使用扩展运算符:
const expected_output = {
...date_dict,
...data_dict
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.