2

Let's say I have this js object:

{"a": null, "b": 5, "c": 0, d: "", e: [1,2,null, 3]}

This is what I would like to get:

{"a": "null", "b": 5, "c": 0, d: "", e: [1,2,"null", 3]}

The only idea I have is to use:

function nullToString(v) {
    return JSON.parse(JSON.stringify(v).split(":null").join(":\"null\""));
}

But it seems like a quite expensive operation comparing with what I would like to achieve.

If there is any helpful method from jQuery or underscore.js that would be great.

10
  • 4
    You can always do it manually by iterating through all object keys (and "subkeys" and so on). It will probably be the fastest solution. Commented Sep 24, 2014 at 12:42
  • I was hoping for some non-imperative solution... Commented Sep 24, 2014 at 12:45
  • Have a look at: [how-to-iterate-json-hashmap][1] [1]: stackoverflow.com/questions/9007065/how-to-iterate-json-hashmap Commented Sep 24, 2014 at 12:46
  • You have already shown short solution. In this situation you should choose between fast work and short code. Commented Sep 24, 2014 at 12:46
  • 1
    Try: JSON.parse(JSON.stringify(...).split("null,").join("\"null\"");. This split-join approach has yielded better results than replace in my case. Commented Sep 24, 2014 at 12:55

2 Answers 2

3

This works for the data you provided:

var data = {"a": null, "b": 5, "c": 0, d: "", e: [1,2,null, 3]};

function nullToString(value) { 

    function recursiveFix(o) {
        // loop through each property in the provided value
        for(var k in o) {
            // make sure the value owns the key
            if (o.hasOwnProperty(k)) { 
                if (o[k]===null) {
                    // if the value is null, set it to 'null'
                    o[k] = 'null';
                } else if (typeof(o[k]) !== 'string' && o[k].length > 0) {
                    // if there are sub-keys, make a recursive call
                    recursiveFix(o[k]);
                }
            }
        }
    }

    var cloned = jQuery.extend(true, {}, value)
    recursiveFix(cloned);
    return cloned;
}

console.log(nullToString(data));

Basic premise is to recursively loop over your object's properties and replace the value if its null.

Of course the root of your question is "I want something faster." I invite you to profile your solution, this one, and any others you come across. Your results may be surprising.

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

9 Comments

jsfiddle.net/euepw79d - too much recursion problem when keys are strings...
@mnowotka I think that was for another answer... Further the function doesn't return anything. It modifies the original value. So console.log(nullToString(value)) will always return undefined. But nullToString(value); console.log(value); will have your updated values.
Oh, I see. I need a function returning something instead of modifying object in place so I can use it as a decorator.
Easy enough, just clone the object. See my update. I'm using jQuery.extend() for the clone, but you can also use _.clone() if you want.
Cloning does make this significantly slower (on par with the Stringify/Split/Join/Parse solutions). if you don't mind that the original object is modified then the cloning is no longer necessary and you can regain the lost speed by simply returning the object when done with it.
|
0

Here is a very simple example:

function convertObjectValuesRecursive(obj, target, replacement) {
	obj = {...obj};
	Object.keys(obj).forEach((key) => {
		if (obj[key] == target) {
			obj[key] = replacement;
		} else if (typeof obj[key] == 'object' && !Array.isArray(obj[key])) {
			obj[key] = convertObjectValuesRecursive(obj[key], target, replacement);
		}
	});
	return obj;
}

The function takes three parameters, the obj, the target value, and the replacement value, and will recursively replace all target values (including values in nested objects) with the replacement value.

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.