[英]build flat array of objects from tree object
I'm struggling with converting nested object to needed format.我正在努力将嵌套的 object 转换为所需的格式。 I want an array containing objects from nested object to suit table data format.
我想要一个包含来自嵌套 object 的对象的数组以适合表数据格式。 Here are links for format example and table i want
这是我想要的格式示例和表格的链接
const data = [
[
"team",
"year",
"product",
"downTime",
"totalCount"
],
{
"metrics": [
24965836704,
25161192
],
"children": [
{
"name": "UNDEFINED",
"metrics": [
14697807552,
6858384
],
"children": [
{
"name": "2021",
"metrics": [
14697807552,
6858384
],
"children": [
{
"name": "UNDEFINED",
"metrics": [
null,
null
]
},
{
"name": "cola",
"metrics": [
14697807552,
6858384
]
}
]
}
]
},
...another object just like above
]
}
]
In short I want this piece of data above to be in form of like:简而言之,我希望上面的这段数据采用如下形式:
[
{ team: 'UNDEFINED', year: '2021', product: 'cola', downTime: 14697807552, totalCount: 6858384},
{ team: 'UNDEFINED', year: '2021', product: 'cola', downTime: 14697807552, totalCount: 6858384},
...
];
Any help is appreciated!任何帮助表示赞赏!
Maybe this works for you.也许这对你有用。 it take the metrics from the final level.
它采用最终级别的指标。
const getFlat = (array, keys, level = 0) => array.flatMap(o => { const q = { [keys[level]]: o.name }, m = Object.fromEntries(keys.slice(-2).map((k, i) => [k, o.metrics[i]])); return o.children? getFlat(o.children, keys, level + 1).map(p => ({...q, ...p })): {...q, ...m }; }), data = [["team", "year", "product", "downTime", "totalCount"], { metrics: [24965836704, 25161192], children: [{ name: "UNDEFINED", metrics: [14697807552, 6858384], children: [{ name: "2021", metrics: [14697807552, 6858384], children: [{ name: "UNDEFINED", metrics: [null, null] }, { name: "cola", metrics: [14697807552, 6858384] }] }] }] }], [keys, { children: array }] = data, result = getFlat(array, keys, 0); console.log(result);
.as-console-wrapper { max-height: 100%;important: top; 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.