Skip to content

[5.x] Reindex numerical array keys in filter_empty modifier#11677

Closed
daun wants to merge 4 commits intostatamic:5.xfrom
daun:fix/filter-empty-keys
Closed

[5.x] Reindex numerical array keys in filter_empty modifier#11677
daun wants to merge 4 commits intostatamic:5.xfrom
daun:fix/filter-empty-keys

Conversation

@daun
Copy link
Copy Markdown
Contributor

@daun daun commented Apr 7, 2025

Currently, the filter_empty modifier only filters the results without reindexing keys, which results in skipped indexes on numerical arrays. This becomes a problem when casting to json. Since the array has missing indexes, it gets stringified into an object instead of an array, breaking js functionality.

This fix consists in making sure that numerical arrays going into the modifier also come out as numerical arrays. Associative arrays and collections are left as is.

Example

<div x-data='{ categories: {{ categories | filter_empty | to_json }} }'>

Before

<div x-data='{ categories: { "1": "shirts", "3": "pants" }'>

After

<div x-data='{ categories: ["shirts", "pants"] }'>

daun added 4 commits April 7, 2025 22:56
Signed-off-by: Philipp Daun <post@philippdaun.net>
Signed-off-by: Philipp Daun <post@philippdaun.net>
Signed-off-by: Philipp Daun <post@philippdaun.net>
Signed-off-by: Philipp Daun <post@philippdaun.net>
@jasonvarga
Copy link
Copy Markdown
Member

jasonvarga commented Apr 7, 2025

Thanks for this but the intention is to keep it similar to $collection->filter() or array_filter().

If you want it reindexed you can chain the values modifier on it.

{{ categories | filter_empty | values | to_json }}

@jasonvarga jasonvarga closed this Apr 7, 2025
@daun daun deleted the fix/filter-empty-keys branch July 8, 2025 14:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants