0

I have found the following suggestions on how to pass parameter by reference using built-in JavaScript functionality:
[Javascript] Pass By Value And Pass By Reference In JavaScript
TypeScript pass by ref parameter [duplicate]

However, none of them work in practice. Consider the following code example:

let data = {
    prop1: '[1,2,3]',
    prop2: '{"abc":"def"}'
}

function parseString(ref prop) {
    if(typeof prop === 'string') {
        prop = JSON.parse(prop);
    }
}

parseString(data.prop1);
parseString(data.prop2);

Using the boxing approach {item: data.prop1} does not work because the box will contain a copy and not a reference to the original data.prop1 property.

How to properly implement the above example?

1 Answer 1

0

One way to implement parseString function is by specifying the parent object and a string to indicate the referenced property. Here is the code that implements the example:

function parseString(data, propName) {
    if (!Object.keys(data).includes(propName)) {
        throw new Error(`Object does not contain key ${propName}.`);
    }

    if(typeof prop === 'string') {
        data[propName] = JSON.parse(data[propName]);
    }
}

parseString(data, 'prop1');
parseString(data, 'prop2');
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.