I’m trying to write a recursive function that receives an object with two branches of nested objects, and at the output returns one object with two properties that contain an array with all the specified values of the input object.
const obj =
{ main:
{ value: { value: 'main value'}
, anotherValue : 'some another value'
}
, offhand:
{ value:
{ value: 'offhand value'
, anotherValue: 'again recursion'
}
}
}
function devider(object) {
if (typeof object == 'string') {
return object;
}
if (typeof object == 'object') {
let data = {
fromMainHand: [],
fromOffHand: []
};
for (const key in object) {
const value = object[key];
if (typeof value == 'string') {
data.fromMainHand.push(devider(value));
data.fromOffHand.push(devider(value));
}
}
return data;
}
}
console.log(devider(obj)); // {fromMainHand: Array(0), fromOffHand: Array(0)}
Must be:
{ fromMainHand : ['main value', 'some another value']
, fromOffHand : ['offhand value', 'again recursion']
}
3
Answers
Several issues:
Your sample input has an object literal with twice the same property. As a consequence, your input does not have the value "offhand value".> (You corrected this later in the question).Your
devider
function returns an object withfromMainHand
andfromOffHand
properties, and so when you make a recursive call, with.push(devider(value))
, you’re adding an object to the array, not a string value or multiple string values. The object with the two properties should only be created once.If the input would have numbers, booleans, or any other primitive value that is not a string, those values are ignored.
I would split this problem into two parts:
The first function is a good candidate for a generator function. So then it looks like this:
In comments you write there should be one recursive function, which can be done in many ways. For instance, you could return the flattened arrays for each property of the given object, returning that new object, and after a recursive you could flatten that object completely to an array:
When creating recursive code, I find a functional appoach is often the simplist way of approaching the task. This is split into the
flattenValues()
function for the nested objects and amapObject()
function to do the first layer.A simpler solution can be achived via using the functional library Ramda. I find this code a bit cleaner and unlike native JS, the
map()
function in Ramda supports objects.You can have a play with this version the Ramda codepen.
In functional programming
identity
is just(x) => x
, we have to pass an else function toifElse()
and this just tells it to do nothing.In both cases I had to tidy up the input data a little, as one object had duplicate keys.
Without additional context about the structure of the object and the specific keys involved, there’s a risk of misinterpreting the data and pushing values to the wrong arrays. More information about the expected structure and keys would help ensure accurate categorization.