I want to do the following: from a JS object, I want to build a second one, listing recursively all properties from the first, but all at 'level one' and whose name is the 'path' inside the first object.
Here is an example. The following object...
{
level1_simple: 'foo',
level1_object: {
level2_a: 'bar',
level2_b: 'bar2'
},
level1_array: [
{
property1: 'foobar',
property2: 'foobar2'
},
'element2'
]
}
Should be translated as:
{
level1_simple: 'foo',
level1_object[level2_a]: 'bar',
level1_object[level2_b]: 'bar2',
level1_array[0][property1]: 'foobar',
level1_array[0][property2]: 'foobar2',
level1_array[1]: 'element2'
}
I've written a recursive function that would work well except for the two following issues I can't manage to solve:
- Strings are parsed as arrays of characters instead of strings
- I do not know how to detect the 'leaf' properties (termination condition), since each property always seems to have a '0' property, which itself has a '0' property, etc.
Here is the full code (that results in an endless loop due to point 2 above):
function _treatDataRecursive( data, newData, prefix )
{
console.log( 'Entering: ' + prefix +"\n" );
// Iterate over the properties of data
for( property in data )
{
console.log( 'Listing properties: ' + property + " value = " + data[property] + "\n" );
// Build property symfonyzed name (using recursion)
var newPropName = prefix + '[' + property + ']';
// Check if property is a leaf
var type = typeof property;
if( type === 'string' || type === 'number' || type === 'boolean' )
{
console.log( 'Property is a leaf: ' + property +"\n" );
// Property is a leaf: add property/value to newData
newData[newPropName] = data[property];
} else {
// Recursive call to go one level deeper
_treatDataRecursive( property, newData, newPropName );
}
}
}