diff --git a/CHANGELOG.md b/CHANGELOG.md index 7070990..92d86f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed - `auto_trim` plugin: Trim comments. - `set` evaluates the expression twice. +- `for`: Make sure key values of an array are always numbers [#83]. ## [1.12.11] - 2024-11-03 ### Fixed @@ -264,6 +265,7 @@ First version [#72]: https://github.com/oscarotero/vento/issues/72 [#73]: https://github.com/oscarotero/vento/issues/73 [#74]: https://github.com/oscarotero/vento/issues/74 +[#83]: https://github.com/oscarotero/vento/issues/83 [1.12.12]: https://github.com/oscarotero/vento/compare/v1.12.11...HEAD [1.12.11]: https://github.com/oscarotero/vento/compare/v1.12.10...v1.12.11 diff --git a/plugins/for.ts b/plugins/for.ts index d2cce06..3b85d0b 100644 --- a/plugins/for.ts +++ b/plugins/for.ts @@ -59,7 +59,9 @@ function toIterator( } if (Array.isArray(item)) { - return withKeys ? Object.entries(item) : item; + return withKeys + ? Object.entries(item).map(([key, value]) => [parseInt(key, 10), value]) + : item; } if (typeof item === "function") { diff --git a/test/for.test.ts b/test/for.test.ts index 1ec8465..bb76d88 100644 --- a/test/for.test.ts +++ b/test/for.test.ts @@ -46,6 +46,13 @@ Deno.test("For tag (array)", async () => { `, expected: "1(0)-2(1)-3(2)-4(3)-", }); + // Fix for issue https://github.com/ventojs/vento/issues/83 + await test({ + template: ` + {{ for key, name of [0, 1, 2, 3] }}{{key == name}}{{key === name}}{{ /for }} + `, + expected: "truetruetruetruetruetruetruetrue", + }); }); Deno.test("For tag (object)", async () => { @@ -72,6 +79,27 @@ Deno.test("For tag (object)", async () => { `, expected: "1(one)-2(two)-", }); + + await test({ + template: ` + {{ for name of names }}{{people[name].surname}}{{ /for }} + `, + expected: "OteroRubio", + data: { + names: [ + "Óscar", + "Laura", + ], + people: { + "Óscar": { + surname: "Otero", + }, + "Laura": { + surname: "Rubio", + }, + }, + }, + }); }); Deno.test("For tag (function)", async () => {