1

How can I write a function that will accept injectionObject and modify currentObject? I believe this is sort of how GraphQL works if I'm not mistaken. I need to achieve this effect in plain 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'
            }
        }
    }
0

1 Answer 1

2

You could take he entries and update the property or visit the nested properties.

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.