如何用menu1的同键值替换menu对象中的对应属性值?
实现方法
当然有可行的实现方式,以下是几种常用的JavaScript方案:
方法一:使用Object.assign()
这个方法会把menu1的可枚举属性复制到menu中,自动覆盖同名键的值,刚好符合你的需求(因为menu1长度≤menu,不会新增menu没有的键):
let menu = {variable: "name", hsn: '630710', operator: 'not one of'} let menu1 = {hsn: '630344', operator: 'not in'} // 直接修改原menu对象 Object.assign(menu, menu1); console.log(menu); // 输出:{variable: "name", hsn: "630344", operator: "not in"}
方法二:遍历menu1的键手动替换
如果需要更精细的控制(比如只替换menu中存在的键,避免意外新增),可以手动遍历menu1的键:
let menu = {variable: "name", hsn: '630710', operator: 'not one of'} let menu1 = {hsn: '630344', operator: 'not in'} Object.keys(menu1).forEach(key => { if (menu.hasOwnProperty(key)) { // 确保menu存在该键再替换 menu[key] = menu1[key]; } }); console.log(menu); // 输出同上
方法三:使用展开运算符创建新对象(不修改原menu)
如果不想修改原menu对象,而是生成一个新的合并对象,可以用展开运算符:
let menu = {variable: "name", hsn: '630710', operator: 'not one of'} let menu1 = {hsn: '630344', operator: 'not in'} const updatedMenu = {...menu, ...menu1}; console.log(updatedMenu); // 输出:{variable: "name", hsn: "630344", operator: "not in"} console.log(menu); // 原menu保持不变
这些方法都能满足你的需求:匹配相同键,用menu1的值替换menu的对应值,且因为menu1的键数量少于等于menu,不会出现menu中没有的键被新增的情况。
内容的提问来源于stack exchange,提问作者bugsmasher
相关产品推荐
相关产品推荐

