在typescript中创建和计数动态对象



我正在尝试从对象的数组中计算一个结果,我可以计算每个键的值,并将其自己的dbId添加到对象名称内的相同计算结果中!这背后的原因是使用它来绘制.js。这样我就可以检查每个结果值是否带有自己的dbIds

const obj = [
{
dbId: 26598,
properties: [
{ attributeName: "BIM7AATypeCode" },
{ displayCategory: "Identity Data" },
{ displayName: "BIM7AATypeCode" },
{ displayValue: "221" },
],
},
{
dbId: 26591,
properties: [
{ attributeName: "BIM7AATypeCode" },
{ displayCategory: "Identity Data" },
{ displayName: "BIM7AATypeCode" },
{ displayValue: "221" },
],
},
{
dbId: 3695,
properties: [
{ attributeName: "abc" },
{ displayCategory: "Identity Data" },
{ displayName: "BIM7AATypeCode" },
{ displayValue: "123" },
],
},
{
dbId: 3697,
properties: [
{ attributeName: "abc" },
{ displayCategory: "Identity Data" },
{ displayName: "BIM7AATypeCode" },
{ displayValue: "123" },
],
},
];
// type Histogram = {
//   [key: string]: number;
// };
let histogram = {}; //as Histogram
for (let iterator of obj) {
for (let { displayName, displayValue } of iterator.properties) {
//@ts-ignore
histogram[displayName] = histogram[displayName] | {};
if (!histogram[displayValue]) {
histogram[displayValue] = 1;
} else {
histogram[displayValue] = histogram[displayValue] + 1;
}
}
}
console.log(histogram);
//expected result:
/*
{
BIM7AATypeCode: {
"221": 2,
dbid: [26598, 26591],
},
abc: {
"123": 2,
dbid: [3695, 3697],
},
};
*/

请找到Array.reduce实现。

逻辑

  • 使用Array.reduce循环通过obj阵列
  • 从阵列中的每个对象中,拾取properties键。从该节点中选择具有作为属性节点的关键字attributeName和作为显示值节点的displayValue的节点
  • 检查累加器是否有一个带有attributeName的节点
  • 若并没有,则将一个节点推送到累加器,其中displayValue具有值1,dbid作为单节点数组
  • 如果累加器已经有这个节点。更新displayValue的计数并推送新的dbid

const obj = [
{ dbId: 26598, properties: [{ attributeName: "BIM7AATypeCode" }, { displayCategory: "Identity Data" }, { displayName: "BIM7AATypeCode" }, { displayValue: "221" }] },
{ dbId: 26591, properties: [{ attributeName: "BIM7AATypeCode" }, { displayCategory: "Identity Data" }, { displayName: "BIM7AATypeCode" }, { displayValue: "221" }] },
{ dbId: 3695, properties: [{ attributeName: "abc" }, { displayCategory: "Identity Data" }, { displayName: "BIM7AATypeCode" }, { displayValue: "123" }] },
{ dbId: 3697, properties: [{ attributeName: "abc" }, { displayCategory: "Identity Data" }, { displayName: "BIM7AATypeCode" }, { displayValue: "123" }] },
];
const output = obj.reduce((acc, curr) => {
const attribute = curr.properties.find(node => node.attributeName);
const displayValue = curr.properties.find(node => node.displayValue);
if (acc[attribute.attributeName]) {
acc[attribute.attributeName][displayValue.displayValue] ? acc[attribute.attributeName][displayValue.displayValue]++ : acc[attribute.attributeName][displayValue.displayValue] = 1;
acc[attribute.attributeName].dbid.push(curr.dbId);
} else {
const newAttribute = {
[displayValue.displayValue]: 1,
dbid: [curr.dbId]
}
acc[attribute.attributeName] = newAttribute;
}
return acc;
}, {});
console.log(output);

相关内容

  • 没有找到相关文章