Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

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',
};
like image 208
camden_kid Avatar asked Aug 24 '26 07:08

camden_kid


1 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.

like image 116
JKillian Avatar answered Aug 26 '26 23:08

JKillian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!