Replace any object field with value empty string to null without iteration?

Viewed 6591

Consider this object:

{
    value1: 'bacon',
    value2: '',
    value3: 'lard',
    value4: '',
    value5: 'cheese',
};

Is there a way to get the following object without iteration?:

{
    value1: 'bacon',
    value2: null,
    value3: 'lard',
    value4: null,
    value5: 'cheese',
};
3 Answers

It's not possible to do without iteration. From an outside function's point of view, your object is simply an arbitrary set of key-value pairs.

That said, you could do it in a single line of code with a library like lodash and its mapValues function:

_.mapValues(myObj, v => v === '' ? null : v)

Or, you could do it yourself without an external library (this example mutates the original object):

Object.keys(myObj).forEach(k => myObj[k] = myObj[k] === '' ? null : myObj[k])

There's another way you can sort of do what you ask, using a Proxy object. This does what you're asking in a lazy sort of way. It won't actively change the values in your object, but when a value is requested, it'll check if it's an empty string and return null if it is:

const proxyObj = new Proxy(myObj, {
  get: (obj, prop) => obj[prop] === "" ? null : obj[prop],
});

// proxyObj.value1
//   => 'bacon'
// proxyObj.value2
//   => null

This Proxy solution may be clever, but the iterative solutions above are the simpler and better choice in most situations.

Another iteration example.

const obj = {
  value1: 'bacon',
  value2: '',
  value3: 'lard',
  value4: '',
  value5: 'cheese',
};

Object.keys(obj).reduce((acc, key) => {acc[key] = obj[key] === '' ? null : 
obj[key]; return acc; }, {})

For anyone who comes across this and these solutions don't work exactly like they want, here's how I solved it for myself. I used a JSON.stringify + JSON.parse(data, reviver) to translate the strings.

let data = {
  value1: 'bacon',
  value2: '',
  value3: 'lard',
  value4: '',
  value5: 'cheese',
};

data = JSON.parse(JSON.stringify(data), (key, value) => {
    return value === '' ? null : value;
});
Related