gpt4 book ai didi

javascript - 按嵌套数组键分组

转载 作者:行者123 更新时间:2023-12-05 03:16:45 25 4
gpt4 key购买 nike

我有一些示例数据显示了一些与文档相关的数据 (docs.id) 以及它所指的人 (details.id) :

const docs = [
{
id: "89",
state: "accepted",
details: [
{
id: 20656,
type: "Claimant",
name: "First Name Last Name",
first_name: "First Name",
last_name: "Last Name",
type_label: "claimant"
}
]
},
{
id: "45",
state: "accepted",
details: [
{
id: 20656,
type: "Claimant",
name: "First Name Last Name",
first_name: "First Name",
last_name: "Last Name",
type_label: "claimant"
},
{
id: 20657,
type: "Fellow",
name: "Fellow First Name Fellow Last Name",
first_name: "Fellow First Name",
last_name: "Fellow Last Name",
type_label: "fellow"
}
]
},
{
id: "47",
state: "rejected",
details: [
{
id: 20656,
type: "Claimant",
name: "First Name Last Name",
first_name: "First Name",
last_name: "Last Name",
type_label: "claimant"
}
]
}
]

const groups = docs.reduce((groups, item) => {
const group = groups[item.details] || [];
group.push(item);
groups[item.details] = group;
return groups;
}, {});

console.log("groups: ", groups);

我正在尝试操纵这个数组,以便我可以将每个人 (details.id) 所有她的相关文档 (docs.id) 分组,这样我就可以稍后在 React 应用程序中使用结果,但它不是那样工作的。

编辑(添加预期结果):

  const new = [
{
id: 20656,
type: "Claimant",
name: "First Name Last Name",
docs: [89,45,47]
},
{
id: 20656,
type: "Fellow",
name: "Fellow First Name Fellow Last Name",
docs: [47]
}
]

最佳答案

  • 使用Array#reduce , 在更新 Map 时遍历 docs其中键是 detail-id,值是 docs array
  • 中累积的详细信息
  • 在每次迭代中,使用Array#forEach 遍历当前详细信息 :
    • 使用Map#get , 获取当前 detail-id 的累积对象,否则使用初始的
    • 使用Array#push , 将 doc-id 添加到它的 docs 数组
    • 使用Map#set , 用新值更新 map
  • 使用Map#values , 返回分组项列表

const docs = [
{
id: "89",
state: "accepted",
details: [
{ id: 20656, type: "Claimant", name: "First Name Last Name", first_name: "First Name", last_name: "Last Name", type_label: "claimant" }
]
},
{
id: "45",
state: "accepted",
details: [
{ id: 20656, type: "Claimant", name: "First Name Last Name", first_name: "First Name", last_name: "Last Name", type_label: "claimant" },
{ id: 20657, type: "Fellow", name: "Fellow First Name Fellow Last Name", first_name: "Fellow First Name", last_name: "Fellow Last Name", type_label: "fellow" }
]
},
{
id: "47",
state: "rejected",
details: [
{ id: 20656, type: "Claimant", name: "First Name Last Name", first_name: "First Name", last_name: "Last Name", type_label: "claimant" }
]
}
];

const groups = [...
docs.reduce((detailMap, { id: docId, state, details = [] }) => {
details.forEach(({ id, type, name }) => {
const detail = detailMap.get(id) ?? { id, type, name, docs: [] };
detail.docs.push(docId);
detailMap.set(id, detail);
});
return detailMap;
}, new Map)
.values()
];

console.log("groups: ", groups);

关于javascript - 按嵌套数组键分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74518738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com