首页 > 解决方案 > 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'
            }
        }
    }

标签: javascriptarraysobject

解决方案


您可以获取他的条目并更新属性或访问嵌套属性。

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; }


推荐阅读