JavaScript:使用 reduce() 和 map() 简化数组导致未定义
Posted
技术标签:
【中文标题】JavaScript:使用 reduce() 和 map() 简化数组导致未定义【英文标题】:JavaScript : Simplifying array with reduce() and map() resulting in undefined 【发布时间】:2021-10-30 13:59:42 【问题描述】:sample = [
key1: 'value1',
key2: 'val1',
key3: [ subkey1: 'a', subkey2: 'b' ]
,
key1: 'value2',
key2: 'val2',
key3: [ subkey1: 'c', subkey2: 'd' ]
,
key1: 'value3',
key2: 'val3',
key3: [ subkey1: 'e', subkey2: 'f' ]
,
key1: 'value3',
key2: 'val3',
key3: [ subkey1: 'g', subkey2: 'h' ]
,
key1: 'value3',
key2: 'val3',
key3: [ subkey1: 'i', subkey2: 'j' ]
,
key1: 'value3', key2: 'val3', key3: [ subkey1: 'k', subkey2: 'l' ]
];
result = Array.from(
this.sample.reduce(
(m, key1, key3, key2 ) =>
m.set(key1, [...(m.get(key1) || []), key3, key2]),
new Map()
),
([key1, key3, key2]) => ( key1, key3, key2 )
);
console.log(result);
我是 javascript 新手,正在尝试对如下所示的对象数组执行分组操作:
sample = [key1: "value1", key2: "val1", key3: [subkey1: "a", subkey2: "b"]
key1: "value2", key2: "val2", key3: [subkey1: "c", subkey2: "d"]
key1: "value3", key2: "val3", key3: [subkey1: "e", subkey2: "f"]
key1: "value3", key2: "val3", key3: [subkey1: "g", subkey2: "h"]
key1: "value3", key2: "val3", key3: [subkey1: "i", subkey2: "j"]
key1: "value3", key2: "val3", key3: [subkey1: "k", subkey2: "l"]]
我尝试使用以下代码根据 key1 值对其进行分组:
const result = Array.from(sample.reduce((m, key1, key3, key2) =>
m.set(key1, [...(m.get(key1) || []), key3, key2]), new Map()), ([key1, key3, key2]) =>
(key1, key3, key2));
但是我得到了这样的东西:
[key1: "value3", key3: [subkey1: "e", subkey2: "f",subkey1: "g",
subkey2: "h",subkey1: "i", subkey2: "j",subkey1: "k", subkey2:
"l"], key2: **undefined**,.....etc]
预期:
[key1: "value3", key3: [subkey1: "e", subkey2: "f",subkey1: "g",
subkey2: "h",subkey1: "i", subkey2: "j",subkey1: "k", subkey2:
"l"],, key2: "val3",.....etc]
key 2 在这里仍未定义。有人可以告诉我我在哪里做错了或任何其他方式来获得预期的结果。
谢谢,
【问题讨论】:
@HR01M8055 分组基于 key1。 【参考方案1】:您错误地使用了Array.from()
和Map
对象,基本上是多余的。
您将 4 个参数传递给 Map.set(),而它只需要 2 个参数。
let m = new Map();
m.set("1","2","3","4"); // essentially just m.set("1","2"), which set the key "1" to value "2";
let array = Array.from(m);
let array2 = Array.from(m,([a,b,c,d])=>return a,b,c,d);
console.log(array);
console.log(array2);
最重要的是您不确定要如何对对象进行分组。您的示例未提供任何信息,因为除了 key1
的值之外的所有值都是相等的。当按key1
的值分组而组成员对key2
和key3
有不同的值时,您期望什么结果?请仔细考虑您的预期输入和输出是什么。设计清晰的数据结构。
【讨论】:
以上是关于JavaScript:使用 reduce() 和 map() 简化数组导致未定义的主要内容,如果未能解决你的问题,请参考以下文章
JavaScript:使用 reduce() 和 map() 简化数组导致未定义
在JavaScript函数式编程里使用Map和Reduce方法
JavaScript 基于reduce方法实现数组内对象的同属性运算
JavaScript 基于reduce方法实现数组内对象的同属性运算
javascript JS:如何使用reduce()function.js #javascript #js #reduce查找数字数组的总和