如何合并对象内的所有数组?属性数量较多时的优化方案及Lodash实现咨询
Absolutely! There are far cleaner, scalable alternatives to repeatedly calling concat—whether you want to stick to vanilla JavaScript or use Lodash. Let’s walk through both approaches:
Vanilla JavaScript Solutions
These methods work out of the box with no external libraries, and they’ll handle any number of array properties in your object without extra code.
1. Spread Operator + concat
This is a straightforward way to merge all arrays in one go:
let fruit = { apple: [1, 2], orange: [3, 4], banana: [5, 6] }; let allFruits = [].concat(...Object.values(fruit)); // Result: [1, 2, 3, 4, 5, 6]
Object.values(fruit)grabs all the array values from your object (returns[[1,2], [3,4], [5,6]])- The spread operator (
...) unpacks these arrays as individual arguments toconcat, merging them into a single array.
2. Array.flat()
If you prefer even shorter code, flat() is perfect for this use case (it works with one level of nesting, which is exactly what we have here):
let allFruits = Object.values(fruit).flat(); // Same result as above
Note: If you ever need to handle deeper nested arrays, you can pass a depth argument like flat(2) to expand multiple levels.
3. Array.reduce()
Great if you need to add custom logic during the merge (like filtering values before combining):
let allFruits = Object.values(fruit).reduce((accumulator, currentArray) => { // Add any custom logic here (e.g., filter odd numbers) return accumulator.concat(currentArray); }, []);
We start with an empty array ([] as the initial value) and iteratively merge each array into the accumulator.
Lodash Solutions
Lodash makes this even simpler, and it’s a solid choice if you need better compatibility with older browsers or want to handle more complex data structures.
1. _.values() + _.flatten()
Combine Lodash’s value extraction and flattening functions:
const _ = require('lodash'); // Import Lodash first let fruit = { apple: [1, 2], orange: [3, 4], banana: [5, 6] }; let allFruits = _.flatten(_.values(fruit));
_.values(fruit)extracts the array values from the object_.flatten()collapses the nested array structure into a single array.
2. _.flatMap()
A one-step solution that combines mapping and flattening:
let allFruits = _.flatMap(fruit, (value) => value);
_.flatMap() first maps over each value (we just return the array itself here) and then automatically flattens the result one level—clean and concise.
All these approaches eliminate the redundancy of calling concat for every array property, making your code easier to maintain even as your object grows to 20+ properties.
内容的提问来源于stack exchange,提问作者Ibrahim Ali

