使用展開運算子從map函數傳回鍵值對的方法
P粉253800312
P粉253800312 2023-08-13 17:18:34
0
1
447
<p>我有一個物件和一個陣列。假設:</p> <pre class="brush:php;toolbar:false;">const first = { 'key1': 'some date', 'key2': 'some date' } const second = ['key3', 'key4']</pre> <p>然後使用擴充語法將它們合併為單一物件。對於數組中的每個項,我想建立一個新的鍵值對,並將其放入這個合併的物件中。目前,我只能從map函數中傳回對象,而不是鍵值對。如何更改這個? </p> <pre class="brush:php;toolbar:false;">const combined = { ....first, ...second.map(key => ({ [key]: new Date() })) // 傳回鍵值對而不是對象 }</pre> <p>我得到的結果:</p> <pre class="brush:php;toolbar:false;">{ '0': { key3: 'some date' }, '1': { key4: 'some date' }, key1: 'some date', key2: 'some date' }</pre> <p>我想要的結果:</p> <pre class="brush:php;toolbar:false;">{ key1: 'some date', key2: 'some date', key3: 'some date', key4: 'some date' }</pre> <p><br /></p>
P粉253800312
P粉253800312

全部回覆(1)
P粉925239921

無法這樣做。 map 輸出一個陣列(其中每個值是透過將原始陣列中匹配索引處的值傳遞給函數的結果)。如果將陣列展開到物件中,您將得到索引(數字)作為屬性名稱和值作為值。

如果您想從陣列開始並以物件結束,那麼map就是錯誤的工具。請改用reduce

類似以下程式碼:

const combined = second.reduce(
    (prev, curr) => {
        return {
            ...prev,
            [curr]: new Date()
        };
    },
    first
);
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!