簡體   English   中英

如何使用 JavaScript 從數據創建嵌套對象?

[英]How to create a nested object from data using JavaScript?

這是一個多行的對象:

  {
  "functions": [
    {
      "package_id": "2",
      "module_id": "2",
      "data_id": "2"
    },
    {
      "package_id": "1",
      "module_id": "1",
      "data_id": "2"
    },
    {
      "package_id": "2",
      "module_id": "3",
      "data_id": "3"
    }
  ]
}

想要的結果

我希望它返回到如下所示的“嵌套”對象中,沒有重復:

{
  "packages": [
    {
      "package_id": "2",
      "modules": [
        {
          "module_id": "2",
          "data": [
            {
              "data_id": "2"
            }
          ]
        },
        {
          "module_id": "3",
          "data": [
            {
              "data_id": "3"
            }
          ]
        }
      ]
    },{
      "package_id": "1",
      "modules": [
        {
          "module_id": "1",
          "data": [
            {
              "data_id": "2"
            }
          ]
        }
      ]
    }
  ]
}

我已經在循環中嘗試過循環,構造多個數組和對象。 這會導致重復或覆蓋對象成為單個對象。 有沒有更通用的方法來用 JavaScript 生成這個? (它用於 Angular (6) 項目。

示例 1

getFunctionPackage() {

        var fList = this.functionList;

        var dArr = [];
        var dObj = {};

        var pArr = [];
        var pObj = {};

        var mArr = [];
        var mObj = {};

        for (var key in fList) {

            pObj['package_id'] = fList[key]['package_id'];
            mObj['module_id'] = fList[key]['module_id'];
            dObj['data_id'] = fList[key]['data_id'];

            for (var i = 0; i < pArr.length; i++) {
                if (pArr[i].package_id != pObj['package_id']) {
                    pArr.push(pObj);
                }
                for (var x = 0; x < mArr.length; x++) {
                    if (pArr[i]['modules'][x].module_id != mObj['module_id']) {
                        mArr.push(mObj);
                    }
                    for (var y = 0; y < dArr.length; y++) {
                        if (pArr[i]['modules'][x]['datas'][y].data_id != dObj['data_id']) {
                            dArr.push(dObj);
                        }
                    }
                }
            }

            if (dArr.length == 0) {
                dArr.push(dObj);
            }
            mObj['datas'] = dArr;

            if (mArr.length == 0) {
                mArr.push(mObj);
            }
            pObj['modules'] = mArr;

            if (pArr.length == 0) {
                pArr.push(pObj);
            }
            dObj = {};
            mObj = {};
            pObj = {};
        }
    }

示例 2:導致跳過布爾值的原因

 var fList = this.functionList;

var dArr = [];
var dObj = {};

var pArr = [];
var pObj = {};

var mArr = [];
var mObj = {};

var rObj = {};

for (var key in fList) {

    pObj['package_id'] = fList[key]['package_id'];
    mObj['module_id'] = fList[key]['module_id'];
    dObj['data_id'] = fList[key]['data_id'];

    var pfound = false;
    var mfound = false;
    var dfound = false;
    
    for (var i = 0; i < pArr.length; i++) {
        if (pArr[i].package_id == pObj['package_id']) {
            for (var x = 0; x < mArr.length; x++) {
                if (pArr[i]['modules'][x].module_id == mObj['module_id']) {
                    for (var y = 0; y < dArr.length; y++) {
                        if (pArr[i]['modules'][x]['datas'][y].data_id == dObj['data_id']) {
                            dfound = true;
                            break;
                        }
                    }
                    mfound = true;
                    break;
                }
            }
            pfound = true;
            break;
        }
    }
    if (!dfound) {
        dArr.push(dObj);
        mObj['datas'] = dArr;
        dObj = {};
    }

    if (!mfound) {
        mArr.push(mObj);
        pObj['modules'] = mArr;
        mObj = {};
    }

    if (!pfound) {
        pArr.push(pObj);
        pObj = {};
    }

    dArr = [];
    mArr = [];
}

rObj['packages'] = pArr;
console.log(rObj);

這是使用Array#reduce()創建基於包 ID 作為鍵的分組對象的更通用方法。 您可以使用任何循環來構建相同的對象……例如for()forEach()

然后使用Object.values()從該分組對象中獲取最終數組

使用Array#find()類的方法Array#find()簡化遍歷以查看模塊是否已存在於每個包中

 const grouped = data.functions.reduce((a, c )=>{ // if group object doesn't exist - create it or use existing one a[c.package_id] = a[c.package_id] || {package_id : c.package_id, modules: [] } // store reference to the group modules array const mods = a[c.package_id].modules // look within that group modules array to see if module object exists let module = mods.find(mod => mod.module_id === c.module_id) if(!module){ // or create new module object module = {module_id: c.module_id, data:[]} // and push it into modules array mods.push(module); } // push new data object to module data array module.data.push({data_id: c.data_id}) return a }, {}) // create final results object const res = { packages : Object.values(grouped) } console.log(res)
 .as-console-wrapper {max-height: 100%!important;}
 <script> const data = { "functions": [{ "package_id": "2", "module_id": "2", "data_id": "2" }, { "package_id": "1", "module_id": "1", "data_id": "2" }, { "package_id": "2", "module_id": "3", "data_id": "3" } ] } </script>

暫無
暫無

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

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