如何使用 lodash 将未知数量的对象合并为一个
How to merge unknown number of object into one using lodash
我正在做一个 react-native 项目,从 api 接收数据就这么简单
[
{
"value":[1,2,3.....1250] //each have max 1250 item, can be have multi of them
},
{
"value":[1,2,3.....1230]
}
]
问题是,我不知道有多少这样的项目,也许 3,4 个对象有 1250 个项目,我不知道,所以我的问题是,如何合并 2 个或任何大于单个对象的对象,如果我们只有 2 个对象,对象值将如下所示:
[
{
"value":[1,2,3...1250,1,2,3..1230]. //will have every value of two object
}
]
我如何在 lodash 中执行此操作?
你不需要 lodash 。您可以使用 JS Reduce 方法简单地做到这一点。
如果你真的想使用 lodash,那么
_ is importing lodash as _
_.reduce(arr, (currentArray, currentValueObject) => ([{
value: [...currentArray[0].value, ...currentValueObject.value] //concatenate current object value to the object valules till now
}]), [{
value: [] //the final value array inside object
}])
var arr = [{
"value": [1, 2, 3, 1250] //each have max 1250 item, can be have multi of them
},
{
"value": [1, 2, 3, 1230]
}
]
var result = arr.reduce((currentArray, currentValueObject) => ([{
value: [...currentArray[0].value, ...currentValueObject.value] //concatenate current object value to the object valules till now
}]), [{
value: [] //the final value array inside object
}])
console.log(result);
我正在做一个 react-native 项目,从 api 接收数据就这么简单
[
{
"value":[1,2,3.....1250] //each have max 1250 item, can be have multi of them
},
{
"value":[1,2,3.....1230]
}
]
问题是,我不知道有多少这样的项目,也许 3,4 个对象有 1250 个项目,我不知道,所以我的问题是,如何合并 2 个或任何大于单个对象的对象,如果我们只有 2 个对象,对象值将如下所示:
[
{
"value":[1,2,3...1250,1,2,3..1230]. //will have every value of two object
}
]
我如何在 lodash 中执行此操作?
你不需要 lodash 。您可以使用 JS Reduce 方法简单地做到这一点。
如果你真的想使用 lodash,那么
_ is importing lodash as _
_.reduce(arr, (currentArray, currentValueObject) => ([{
value: [...currentArray[0].value, ...currentValueObject.value] //concatenate current object value to the object valules till now
}]), [{
value: [] //the final value array inside object
}])
var arr = [{
"value": [1, 2, 3, 1250] //each have max 1250 item, can be have multi of them
},
{
"value": [1, 2, 3, 1230]
}
]
var result = arr.reduce((currentArray, currentValueObject) => ([{
value: [...currentArray[0].value, ...currentValueObject.value] //concatenate current object value to the object valules till now
}]), [{
value: [] //the final value array inside object
}])
console.log(result);