很抱歉这么长时间后碰到这个问题,但我找不到我会这样做的方法。
我会采用更简单(但可能不太优化)的 ES6 方法:
我们从表开始
const table = [
{ group: "a", stuff: "new" },
{ group: "a", stuff: "old" },
{ group: "b", stuff: "newOld" },
{ group: "b", stuff: "old" },
{ group: "c", stuff: "new" },
{ group: "c", stuff: "old" },
{ group: "c", stuff: "newOld" }
];
然后我们希望所有唯一的组值作为一个数组,以便我们可以轻松地在一个选择元素中循环它。
// Get all unique group entries in the table and map them to the value of group
const uniqueGroups = table.filter((entry, index, self) => {
// findIndex will return the index of the first found result
return self.findIndex(a => a.group === entry.group) === index;
).map(entry => entry.group);
为了争论,假设有人点击了一个组。
// Image someone clicked on the group "c"
const chosenGroup = uniqueGroups[2]; // This would be the event handler value of the chosen option
然后我们过滤掉表中与该组值对应的所有条目,并将这些条目映射到 stuff 值。
// Get all stuff related to chosen group
const stuff = table.filter(entry => entry.group === chosenGroup).map(entry => entry.stuff);
我认为这对于少量数据来说更容易并且完全没问题。