簡體   English   中英

在 JavaScript 中將數據結構轉換為樹數據

[英]Transform data structure to tree data in JavaScript

我有一個這樣的數據結構:

 data = [
    {
      parent: {name: 'Sheet'},
      firstArray: [{sampleVar: 0.3, typeName: 'active'}, {sampleVar: 0.4, typeName: 'active'}],
      secondArray: [{sampleVar: 1.2, typeName: 'passive'}, {sampleVar: 1.3 , typeName: 'passive'}]
    },...
  ]

我想將其轉換為這樣的樹數據:

  treeData = [
    {
      parent: {
        name: 'Sheet',
        children: [{
          typeName: 'active',
          children: [
            {sampleVar: 0.3},
            {sampleVar: 0.4}
          ]
        },
          {
            typeName: 'passive',
            children: [
              {sampleVar: 1.2},
              {sampleVar: 1.3}
            ]
          },...
        ]
      },...
    }
  ];

我不得不提到我的變量typeName對於每個數組都有相同的值。 有誰知道實現這一目標的好方法?

您可以使用Object.valuesmap來獲得結果。 我使用了一個變化更大的示例輸入:

 const data = [{ parent: {name: 'SheetA'}, justOne: [{sampleVar: 0.3, typeName: 'active'}], hasTwo: [{indicator: 1.2, typeName: 'passive'}, {indicator: 1.3 , typeName: 'passive'}] }, { parent: {name: 'SheetB'}, hasThree: [{otherVar: 9.3, typeName: 'selected'}, {otherVar: 9.4, typeName: 'selected'}, {otherVar: 9.5, typeName: 'selected'}], secondArray: [{message: 7.2, typeName: 'locked'}, {message: 7.3 , typeName: 'locked'}] }]; const treeData = data.map(({parent, ...rest}) => ({ ...parent, children: Object.values(rest).map(arr => ({ typeName: arr[0]?.typeName, children: arr.map(({typeName, ...rest}) => rest) })) })); console.log(treeData);

考慮到每個數組有 2 個項目,只有每個數組都有自己的類型名,這是可行的。

var result = [
    {
        parent: {
            name: data[0].parent.name,
            children: []
        }
    }
];

for (const property in data[0]) {
    if (property == "parent") continue;
    let array = data[0][property];
    result[0].parent.children.push({
        typeName: array[0].typeName,
        children: [
            {
                sampleVar: array[0].sampleVar
            },
            {
                sampleVar: array[1].sampleVar
            }
        ]
    });
}

console.log(result);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM