data icon indicating copy to clipboard operation
data copied to clipboard

Array.flatMap fails to flatten hasMany relationship

Open robbytx opened this issue 3 years ago • 2 comments

Reproduction

https://ember-twiddle.com/b7a9c880dafac7c885d8aa39dd2ee2e6

Description

hasMany relationships return an array-like object that functions in most ways like a real array. However, they do not behave like an array when returned in the callback function to Array.flatMap, which was quite surprising.

It appears that this is because they do not meet the Array.isArray criteria, as outlined in the ECMAScript spec.

To workaround, I've found that invoking .slice() on the relationship will return a true array, which behaves as expected.

Versions

3.20 (locally) 3.18 (Ember Twiddle)

robbytx avatar Feb 25 '22 20:02 robbytx

This is unsurprising because they aren't arrays! We don't expect them to pass an isArray check, only a native array can pass that check. using toArray or slice to cast to an array first is the expected way to approach situations like this.

runspired avatar Feb 28 '22 07:02 runspired

That's fair, and honestly the response that I expected. I think the surprising part as a developer is that Ember Data's ManyArray behaves like a JavaScript Array in most other ways, including in the fact that .slice works as expected!

If it were possible for Ember Data to address this, I would wholeheartedly appreciate it, but if this is not possible to be fixed, then I'm fine if you want to close this. The existence of this GitHub issue itself is sufficient for my purpose of documenting this behavior and the necessary workaround.

robbytx avatar Feb 28 '22 15:02 robbytx

This should have been handled by the move to native array proxies in 4.7+, re-open if it was not <3

runspired avatar Nov 17 '22 02:11 runspired