簡體   English   中英

如何在給定索引下將一個不變列表中的所有元素插入到另一個中

[英]How to insert all elements from one immutable list into another at given index

我需要將數組(純JS)的內容插入到給定索引的不可變列表中。

我有一個像[a,b,c,d,e]的列表[a,b,c,d,e]它表示服務器上索引0 - 4的ID。 然后,我獲取一個數組[j,k,l,m,n] (它表示索引9 - 14處的id)。 我想合並兩個列表,以便擁有:

[a,b,c,d,e,undefined,undefined,undefined,undefined,undefined,j,k,l,m,n]

可以執行oldList.insert(9, nextList)但這oldList.insert(9, nextList)整個nextList數組嵌套到索引9而不是其內容位於索引9 - 14

我需要類似ES6 / Next傳播算子的東西。

const ids = oldList.insert(10, ...next_ids)

但這是不可能的。

有任何想法嗎?

這是我當前的解決方案,但有興趣知道是否還有更簡潔的方法。

const list = List( ['a', 'b', 'c', 'd', 'e'] ) // Indices 0 - 5
const fetchResponse = ['j', 'k', 'l', 'm', 'n'] // Indices 9 - 14
const nextList = List()
  .setSize(9) // The start index of fetched results
  .concat(List(fetchResponse))
  .mergeWith((next, last) => next || last, list) // Take new value at index if defined, otherwise old

console.log(nextList.toJS())
  -> ['a', 'b', 'c', 'd', 'e', null, null, null, null, null, 'j', 'k', 'l', 'm', 'n']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM