JavaScript单行代码:将对象数组值转为单元素数组构成的数组
Solution for Transforming Your JavaScript Object to the Target Array Structure
Got it, I see exactly what you need here. You already know Object.values(obj) gives you an array of the object's array values (like [["xxx@yyy.com", "qqq@www.com"], ["asdf"], ...]), but you need to break each individual element out into its own single-element array and combine them all into one big array.
Here's the cleanest way to do this using modern JavaScript:
// Your original object let obj = { emails: ["xxx@yyy.com", "qqq@www.com"], nickname: ["asdf"], // Add any other properties here }; // Transform to the target structure let obj2 = Object.values(obj).flatMap(arr => arr.map(item => [item])); console.log(obj2); // Output: [["xxx@yyy.com"], ["qqq@www.com"], ["asdf"], ...]
How this works:
Object.values(obj)grabs all the array values from your object, giving you a nested array like[["xxx@yyy.com", "qqq@www.com"], ["asdf"]].flatMap()does two things in one step:- First, it uses
map(item => [item])on each sub-array to turn every element into a single-element array (e.g.,["xxx@yyy.com"]instead of just the string). - Then it automatically flattens the result by one level, merging all those single-element arrays into the final top-level array.
- First, it uses
For older environments that don't support flatMap:
If you need to support older browsers or environments without flatMap, you can use concat with the spread operator instead:
let obj2 = [].concat(...Object.values(obj).map(arr => arr.map(item => [item])));
This works by:
- Using
mapto turn each sub-array into a list of single-element arrays (same as before). - Spreading those lists into individual arguments for
concat, which merges them all into one array.
Either approach will give you exactly the obj2 structure you're looking for!
内容的提问来源于stack exchange,提问作者andcl
相关产品推荐
相关产品推荐

