Forráskód Böngészése

Support object destructuring in x-for expression (#2012)

Caleb Porzio 3 éve
szülő
commit
e14bfcad0a

+ 7 - 0
packages/alpinejs/src/directives/x-for.js

@@ -239,6 +239,13 @@ function getIterationScopeVariables(iteratorNames, item, index, items) {
         names.forEach((name, i) => {
             scopeVariables[name] = item[i]
         })
+    // Support object destructuring ({ foo: 'oof', bar: 'rab' }).
+    } else if (/^\{.*\}$/.test(iteratorNames.item) && ! Array.isArray(item) && typeof item === 'object') {
+        let names = iteratorNames.item.replace('{', '').replace('}', '').split(',').map(i => i.trim())
+
+        names.forEach(name => {
+            scopeVariables[name] = item[name]
+        })
     } else {
         scopeVariables[iteratorNames.item] = item
     }

+ 19 - 0
tests/cypress/integration/directives/x-for.spec.js

@@ -77,6 +77,25 @@ test('can destructure arrays',
     }
 )
 
+test.only('can destructure object',
+    html`
+        <div x-data="{ items: [{ foo: 'oof', bar: 'rab' }, { foo: 'ofo', bar: 'arb' }] }">
+            <template x-for="({ foo, bar }, i) in items">
+                <div x-bind:id="i + 1">
+                    <span x-text="foo"></span>
+                    <h1 x-text="bar"></h1>
+                </div>
+            </template>
+        </div>
+    `,
+    ({ get }) => {
+        get('#1 span').should(haveText('oof'))
+        get('#1 h1').should(haveText('rab'))
+        get('#2 span').should(haveText('ofo'))
+        get('#2 h1').should(haveText('arb'))
+    }
+)
+
 test('removes all elements when array is empty and previously had one item',
     html`
         <div x-data="{ items: ['foo'] }">