Iteration is necessary in order to achieve this task. From the perspective of an external function, your object is regarded as a random collection of key-value pairs.
One efficient way to accomplish this is by using a library such as lodash and its mapValues
function:
_.mapValues(myObj, val => val === '' ? null : val)
Alternatively, you can achieve this without relying on an external library (this example modifies the original object):
Object.keys(myObj).forEach(key => myObj[key] = myObj[key] === '' ? null : myObj[key])
Another approach to partially address your requirement is by using a Proxy
object. This method offers a lazy solution where the object values are not actively changed, but will return null when an empty string is encountered:
const proxyObj = new Proxy(myObj, {
get: (obj, prop) => obj[prop] === "" ? null : obj[prop],
});
// proxyObj.value1
// => 'bacon'
// proxyObj.value2
// => null
While the Proxy solution is creative, the iterative solutions provided above are generally more straightforward and preferable in most scenarios.