如何连接数组不可变的方式JS
How to concat arrays immutable way JS
我想知道如何联系不可变的数组。假设我从数组 list = [4,1]
开始,然后我从动作响应中接收到数组 items = [5,2,6]
。我如何连接结果为 [4,1,5,2,6]
且该操作不可变的数组。
奖励:如何覆盖具有相同 ID 的项目(不可变方式)?让我们想象一下我们在商店 books=[{'id':1, 'title': 'Cool story'}, {'id':2, 'title': 'Bad story'}]
中的数组。需要覆盖书籍的其他阵列(上次同步来自 API)otherArray = [{'id':3, 'title': 'Super story'}, {'id':1, 'title': 'Very cool story'}]
。所以结果应该是 [{'id':2, 'title': 'Bad story'}], {'id':3, 'title': 'Super story'}, {'id':1, 'title': 'Very cool story'}]
Javascript 没有不可变类型。
听起来您实际上是在要求连接数组而不改变现有实例。
正如 documentation 中明确指出的那样,concat()
方法可以做到这一点。
尽管如前所述,内置方法 .concat()
可以解决您的问题,但您可能希望查看 Lodash library。特别是,奖金问题可以用 _.unionBy(otherArray, books, "id")
.
来解决
使用 ES6 你可以使用解构:
const array1 = ["Banana","Apple"];
const array2 = ["Pineapple", "Peach"];
const array3 = [...array1, ...array2];
arr1.push(...arr2)
我想知道如何联系不可变的数组。假设我从数组 list = [4,1]
开始,然后我从动作响应中接收到数组 items = [5,2,6]
。我如何连接结果为 [4,1,5,2,6]
且该操作不可变的数组。
奖励:如何覆盖具有相同 ID 的项目(不可变方式)?让我们想象一下我们在商店 books=[{'id':1, 'title': 'Cool story'}, {'id':2, 'title': 'Bad story'}]
中的数组。需要覆盖书籍的其他阵列(上次同步来自 API)otherArray = [{'id':3, 'title': 'Super story'}, {'id':1, 'title': 'Very cool story'}]
。所以结果应该是 [{'id':2, 'title': 'Bad story'}], {'id':3, 'title': 'Super story'}, {'id':1, 'title': 'Very cool story'}]
Javascript 没有不可变类型。
听起来您实际上是在要求连接数组而不改变现有实例。
正如 documentation 中明确指出的那样,concat()
方法可以做到这一点。
尽管如前所述,内置方法 .concat()
可以解决您的问题,但您可能希望查看 Lodash library。特别是,奖金问题可以用 _.unionBy(otherArray, books, "id")
.
使用 ES6 你可以使用解构:
const array1 = ["Banana","Apple"];
const array2 = ["Pineapple", "Peach"];
const array3 = [...array1, ...array2];
arr1.push(...arr2)