[英]JavaScript flatMap() error: “flatMap mapper function is not callable”
I am trying to flatten an array with the following code, but when I use .flatMap()
I get the error:我正在尝试使用以下代码展平数组,但是当我使用
.flatMap()
时出现错误:
Uncaught TypeError: flatMap mapper function is not callable
at Array.flatMap (<anonymous>)
const data = [
{ key1: 5, key3: 2 },
{ key1: 2, key3: 1 },
{ key1: 3, key3: 2 },
{ key2: 8 },
{ key1: 5, key3: 2 },
];
var allKeys = data.map(r => Object.keys(r))
// [
// [ 'key1', 'key3' ],
// [ 'key1', 'key3' ],
// [ 'key1', 'key3' ],
// [ 'key2' ],
// [ 'key1', 'key3' ]
// ]
allKeys.flatMap();
In this case I should be using flat()
not flatMap()
.在这种情况下,我应该使用
flat()
而不是flatMap()
。 The below works as expected.以下按预期工作。
const data = [ { key1: 5, key3: 2 }, { key1: 2, key3: 1 }, { key1: 3, key3: 2 }, { key2: 8 }, { key1: 5, key3: 2 }, ]; var allKeys = data.map(r => Object.keys(r)) console.log(allKeys.flat());
You could use flatMap
instead of map
to be more concise, which eliminates the need for calling .flat()
after, as it is just shorthand for .map(...).flat()
.您可以使用
flatMap
而不是map
更简洁,这消除了之后调用.flat()
的需要,因为它只是.map(...).flat()
的简写。 As well, you can directly pass Object.keys
as the callback for flatMap
, as it ignores all arguments other than the first one that it is given.同样,您可以直接传递
Object.keys
作为flatMap
的回调,因为它忽略了除给出的第一个 arguments 之外的所有 arguments。
const data = [ { key1: 5, key3: 2 }, { key1: 2, key3: 1 }, { key1: 3, key3: 2 }, { key2: 8 }, { key1: 5, key3: 2 }, ]; var allKeys = data.flatMap(Object.keys) console.log(allKeys);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.