[英]How to insert all elements from one immutable list into another at given index
I need to insert the contents of an array (pure JS) into an immutable List at a given index. 我需要将数组(纯JS)的内容插入到给定索引的不可变列表中。
I have a list like [a,b,c,d,e]
which represents the ids at indexes 0 - 4
on the server. 我有一个像
[a,b,c,d,e]
的列表[a,b,c,d,e]
它表示服务器上索引0 - 4
的ID。 I then fetch an array [j,k,l,m,n]
(which represents the id's at indices 9 - 14
). 然后,我获取一个数组
[j,k,l,m,n]
(它表示索引9 - 14
处的id)。 I want to merge the two lists so that I have: 我想合并两个列表,以便拥有:
[a,b,c,d,e,undefined,undefined,undefined,undefined,undefined,j,k,l,m,n]
It's possible to do oldList.insert(9, nextList)
but this nests the whole nextList
array into index 9
and not it's contents at indices 9 - 14
可以执行
oldList.insert(9, nextList)
但这oldList.insert(9, nextList)
整个nextList
数组嵌套到索引9
而不是其内容位于索引9 - 14
I need something like the ES6/Next spread operator.. 我需要类似ES6 / Next传播算子的东西。
const ids = oldList.insert(10, ...next_ids)
But this isn't possible. 但这是不可能的。
Any ideas? 有任何想法吗?
Here is my current solution but be interested to know if there is a more succinct way.. 这是我当前的解决方案,但有兴趣知道是否还有更简洁的方法。
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.