首頁  >  問答  >  主體

使用展開運算子從map函數傳回鍵值對的方法

<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粉253800312P粉253800312434 天前455

全部回覆(1)我來回復

  • P粉925239921

    P粉9252399212023-08-14 14:46:08

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

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

    類似以下程式碼:

    const combined = second.reduce(
        (prev, curr) => {
            return {
                ...prev,
                [curr]: new Date()
            };
        },
        first
    );
    

    回覆
    0
  • 取消回覆