javascript - javascript 多级对象操作
问题描述
如何编写一个接受 injectionObject 并修改 currentObject 的函数?如果我没记错的话,我相信这就是 GraphQL 的工作原理。我需要在普通的 JS 中实现这个效果。
//Object to inject into current object
const injectionObject = {
pages: {
about: {
title: 'Changed About Page'
}
}
}
//Object that requires modification based on above object
const currentObject = {
pages: {
home: {
title: 'Home Page',
description: 'This is the home page'
},
about: {
title: 'About Page',
description: 'This is the about page'
}
}
}
//output
const outputObject = {
pages: {
home: {
title: 'Home Page',
description: 'This is the home page'
},
about: {
title: 'Changed About Page', //Only this was affected
description: 'This is the about page'
}
}
}
解决方案
您可以获取他的条目并更新属性或访问嵌套属性。
const
update = (target, source) => Object.entries(source).forEach(([k, v]) => {
if (v && typeof v === 'object') update(target[k] = target[k] || {}, v);
else target[k] = v;
}),
injectionObject = { pages: { about: { title: 'Changed About Page' } } },
currentObject = { pages: { home: { title: 'Home Page', description: 'This is the home page' }, about: { title: 'About Page', description: 'This is the about page' } } };
update(currentObject, injectionObject);
console.log(currentObject);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- algorithm - Find the all possible multiples( size of n ) of a positive integer k
- compilation - 无法使用库编译
- c - CreateFile() 和 CreateFileA() 有什么区别?
- python - Python中如何及时去除T和Z
- javascript - 视频标签加载元数据事件不适用于多个视频标签
- c# - 将数据传递给控制器失败(正在使用元组)
- java - Android Studio 原始文件错误背景音乐
- javascript - 遍历对象数组,检查匹配的参数并将匹配的对象添加到新数组
- java - 除了单词开头的元音之外,我如何从字符串中排除元音?
- html - 内联块不起作用