可以使用Lodash库中的flatten方法将对象数组中的字段数组展开。这个库对JavaS
cr
i
pt
的数组进行了扩展和封装,提供了更多的便利和功能。
示例代码:
// 引入lodash
import _ from 'lodash';
const data = [
{ name: 'Alice', scores: [80, 85] },
{ name: 'Bob', scores: [70, 75, 80] }
// 使用_.flatten方法展开scores字段
const flattened = _.flatten(data.map(d => d.scores));
console.log(flattened); // [80, 85, 70, 75, 80]
上述代码首先引入了Lodash库,然后定义了一个包含两个对象的数组data,每个对象包含一个名字和一个成绩数组。然后使用map方法遍历数组data,取出每个对象的成绩数组并使用flatten方法将其展开。最终将展开后的数组打印输出。
参考文献:
Lodash: https://lodash.com/
Lodash.flatten: https://lodash.com/docs/4.17.15#flatten