Pregunta

I have an object which contains a variety of properties (and sub properties) which may be strings, functions, dates etc.

I would like to recursively loop through all properties and sub properties and if they are a string I'd like to run them through a function to transform them.

Specifically, I'd like to search the object for properties which are strings containing ISO date formats and transform them into friendly looking dates, but that's probably unimportant here as I already know how to transform the strings.

Anyway, I tried cloneDeep, but that didn't seem to work how I wanted it to. Is there a function to do this?

¿Fue útil?

Solución

This seems useful enough: https://github.com/documentcloud/underscore-contrib/, especially the walk extension.

_.walk.preorder(yourObject, function (value, key, parent) {
    if ( _.isString(value) ) {
       parent[key] = "transformed " + parent[key];
    }
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top