Array.map(fn) habit error
Recently I have been working on simple function for flattening object in JS. I have nesting object (depth is undefined) and I needed to convert it to flat object.
to:
So I created function flatten and used it directly on object flatten(obj) and that worked fine.
Then in some cases I needed to convert array of those objects. So I just applied
itemsArr.map(flattenObject)
This function was used primarily in cases when we had only one object, but sometimes I was getting bug reports saying about problems when we needed to convert multiple objects.
As you might realize from the code above problem was related to how callbacks in .{map,reduce,ect} work.
When multiple items needed to be processed first call was:
flattenObject(item1, idx1, itemsArr)
and on line 8 composedKey = (parentKey ? parentKey + ‘.’ : ‘’) + key because parentKey = 0. But for next objects parentKey would be > 0, and I have been getting ‘1.fieldName’.
That’s something that everybody knows about but that may be forgotten especially because usually we are not using second and third parameter of map function.
I guess it may be candidate to be added to linting tools like ESLint, JSHint.