数据数组
[
{group: 'a', tab: "1", name: 'input1'},
{group: 'b', tab: "1", name: 'input2'},
{group: 'b', tab: "1", name: 'input3'},
{group: 'c', tab: "2", name: 'input4'},
{group: 'a', tab: "1", name: 'input5'},
{group: 'c', tab: "2", name: 'input6'},
];
在我的应用程序中,每个数组元素(其中有50多个)都是一个输入,它属于一组(a,b或c)和制表符(1、2等)。我想做的是检查一个选项卡有多少组,得到一个看起来像这样的对象或数组:
[
{tab1:{groups: ["a", "b"]}},
{tab2:{groups: ["c"]}},
]
答案 0 :(得分:1)
您只需使用Array.reduce()
来创建地图并按Tab键将其分组,地图上的Object.values()
将为您提供所需的结果。
let arr =[ {group: "a", tab: "1", name: "input1"}, {group: "b", tab: "1", name: "input2"}, {group: "b", tab: "1", name: "input3"}, {group: "c", tab: "2", name: "input4"}, {group: "a", tab: "1", name: "input5"}, {group: "c", tab: "2", name: "input6"}];
let result = Object.values(arr.reduce((a, {group, tab})=>{
a[tab] = a[tab] || {["tab"+tab] : {group : []}};
if(!a[tab]["tab"+tab].group.includes(group))
a[tab]["tab"+tab].group.push(group);
return a;
},{}));
console.log(result);
:
答案 1 :(得分:1)
我们可以使用Set创建唯一的数组,并使用map操纵每个数组项,并使用filter从数组中删除元素。所以我要做的是:
它看起来像这样:
let data = [
{group: 'a', tab: "1", name: 'input1'},
{group: 'b', tab: "1", name: 'input2'},
{group: 'b', tab: "1", name: 'input3'},
{group: 'c', tab: "2", name: 'input4'},
{group: 'a', tab: "1", name: 'input5'},
{group: 'c', tab: "2", name: 'input6'},
];
let tabs = [...new Set(data.map(itm => itm.tab))].map(tab => {
return {
['tab' + tab]: {groups: [...new Set(data.filter(i => i.tab == tab).map(i => i.group))]}
}
})
console.log(tabs)
答案 2 :(得分:0)
var data = [{ group: 'a', tab: '1', name: 'input1' }, { group: 'b', tab: '1', name: 'input2' }, { group: 'b', tab: '1', name: 'input3' }, { group: 'c', tab: '2', name: 'input4' }, { group: 'a', tab: '1', name: 'input5' }, { group: 'c', tab: '2', name: 'input6' }],
result = Array.from(
data.reduce(
(m, { tab, group }) => m.set(tab, (m.get(tab) || new Set).add(group)),
new Map
),
([tab, groups]) => ({ ['tab' + tab]: { groups: Array.from(groups) } })
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 3 :(得分:0)
尝试下一个代码
const src = [
{ group: "a", tab: "1", name: "input1" },
{ group: "b", tab: "1", name: "input2" },
{ group: "b", tab: "1", name: "input3" },
{ group: "c", tab: "2", name: "input4" },
{ group: "a", tab: "1", name: "input5" },
{ group: "c", tab: "2", name: "input6" },
];
const convert = (src) => {
const dst = [];
Object.keys(src).forEach((item) => {
const tab = `tab${src[item].tab}`;
// Check if dst[tab] does not exist
if (typeof (dst[tab]) === 'undefined') {
dst[tab] = { groups: [] };
}
// Check if groups contains group
if (!dst[tab].groups.includes(src[item].group)) {
dst[tab].groups.push(src[item].group);
}
});
return dst;
};
console.log(convert(src));