如何合并两个对象,仅保留指定对象或数组的键?
解决对象合并仅保留指定键的问题
你遇到的核心问题是扩展运算符会保留第一个对象的所有键,无法自动过滤掉不在第二个对象(或指定键集合)中的键,同时需要优先使用第一个对象的对应值,缺失时用null填充。下面提供两种直接可行的解决方案:
方案一:基于第二个对象的键进行合并
遍历第二个对象的所有键,优先取第一个对象的对应值,无值则用第二个对象的null:
function mergeWithSecondKeys(first, second) { return Object.fromEntries( Object.keys(second).map(key => [key, first[key] ?? second[key]]) ); } // 测试示例1 const first = { "name": "John", "address": "London" } const second = { "name": null, "email": null } console.log(mergeWithSecondKeys(first, second)); // 输出:{ name: 'John', email: null } // 测试示例2 const first2 = { "name": "John", "email": "john@john.com", "address": "London" } const second2 = { "name": null, "email": null } console.log(mergeWithSecondKeys(first2, second2)); // 输出:{ name: 'John', email: 'john@john.com' }
逻辑说明:
Object.keys(second)获取第二个对象的所有目标键,确保结果只包含这些键first[key] ?? second[key]使用空值合并运算符,优先取第一个对象的有效值(非null/undefined),缺失时用第二个对象的默认值Object.fromEntries把键值对数组转换为最终对象
方案二:直接指定键数组(更简便)
如果把第二个对象换成键数组,代码会更简洁,直接遍历指定键集合:
function mergeWithSpecifiedKeys(first, targetKeys) { return Object.fromEntries( targetKeys.map(key => [key, first[key] ?? null]) ); } // 测试示例 const first = { "name": "John", "address": "London" } const targetKeys = ["name", "email"]; console.log(mergeWithSpecifiedKeys(first, targetKeys)); // 输出:{ name: 'John', email: null } const first2 = { "name": "John", "email": "john@john.com", "address": "London" } console.log(mergeWithSpecifiedKeys(first2, targetKeys)); // 输出:{ name: 'John', email: 'john@john.com' }
逻辑说明:
直接遍历指定的目标键数组,每个键优先取第一个对象的值,无值则填充null,最终转换为对象。
为什么扩展运算符无法实现?
{...first, ...second} 的逻辑是先复制第一个对象的所有键值对,再用第二个对象的键值对覆盖重复键,但不会过滤掉第一个对象中不在第二个对象里的键(比如示例中的address),所以无法得到仅保留目标键的结果。
内容的提问来源于stack exchange,提问作者saydiva
相关产品推荐
相关产品推荐

