如何对JSON的类似子项进行分组

时间:2018-04-27 10:30:03

标签: javascript arrays json angular

我想将我的Json的类似子项分组为一个,然后将所有子项合并到该创建的项目下。

这是我的json文件:

{
    "car": [
        {
            "name": "benz",
            "details": [
                {
                    "name": "C1",
                    "year": [
                        {
                            "name": "1850",
                            "errs": [
                                {
                                    "user": "model-A",
                                    "text": "error text on model-H"
                                },
                                {
                                    "user": "model-C",
                                    "text": "error text on model-C"
                                }
                            ]
                        },
                        {
                            "name": "1820",
                            "errs": [
                                {
                                    "user": "model-C",
                                    "text": "error text on model-C"
                                }
                            ]
                        }
                    ]
                }
            ]
        },
        {
            "name": "vw",
            "details": [
                {
                    "name": "A1",
                    "year": [
                        {
                            "name": "1860",
                            "errs": []
                        },
                        {
                            "name": "1870",
                            "errs": [
                                {
                                    "user": "model-A",
                                    "text": "error text on model-H"
                                }
                            ]
                        }
                    ]
                },
                {
                    "name": "A2",
                    "year": [
                        {
                            "name": "1910",
                            "errs": []
                        },
                        {
                            "name": "1950",
                            "errs": [
                                {
                                    "user": "model-A",
                                    "text": "error text on model-H"
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}

我的树结构基于标签和子项,因此我的父项是标签,子树是子项。

这是我的ts文件:

ngOnInit():void {
    this.http.get('.car.json').subscribe((data) => {

        data.car.forEach((carItem) => {

            carItem.details.forEach((detail) => {
                const errorsTree = {};

                detail.year.forEach((year) => {

                    year.errs.forEach((err) => {
                        let userNode;
                        let carNode;
                        let detailNode;

                        if (errorsTree[err.userAgent]) {
                            userNode = errorsTree[err.userAgent];
                        } else {
                            userNode = {name: err.userAgent, cars: {}};
                            errorsTree[err.userAgent] = userNode;
                        }

                        const components = userNode.cars;

                        if (components[carItem.name]) {
                            carNode = cars[carItem.name];
                        } else {
                            carNode = {name: carItem.name, details: {}};
                            components[carItem.name] = carNode;
                        }

                        const detailsItems = carNode.details;

                        if (detailsItems[detail.name]) {
                            detailNode = detailsItems[detail.name];
                        } else {
                            detailNode = {name: detail.name, tests: {}};
                            detailsItems[detail.name] = detailNode;
                        }

                        detailNode.tests[test.name] = test;

                        this.TreeModel.push({
                            label: userNode.name,
                            children: _.values(userNode.cars).map((car) => {
                                return {
                                    label: car.name,
                                    children: _.values(car.details).map((deta) => {
                                        return {
                                            label: deta.name,
                                            children: _.values(deta.tests).map((testItem) => {
                                                return {
                                                    label: testItem.name,
                                                    err: err.text
                                                };
                                            })
                                        };
                                    })
                                };
                            })
                        });

                    });

                });

            });


        });

    });
}

运行代码后,树将如下所示:

model-A
       benz
            C1
model-C
       benz
            C1
model-C
       benz
            C1
model-A
       vw
            A1
model-A
       vw
            A2

但不正确,结果如下:

[
    {
        label: 'model-A',
        children: [
            {
                label: 'benz',
                children: [
                    {
                        label: 'C1'
                    }
                ]
            },
            {
                label: 'vw',
                children: [
                    {
                        label: 'A1'
                    },
                    {
                        label: 'A2'
                    }
                ]
            }
        ]
    },
    {
        label: 'model-C',
        children: [
            {
                label: 'benz',
                children: [
                    {
                        label: 'C1'
                    }
                ]
            }
        ]
    }
]

你是否知道如何使用Angular 5将这个Json分组为上述结构 感谢。

2 个答案:

答案 0 :(得分:3)

你可以使用这样的东西 -

var processedJSON = {};
const data = {
  "car": [{
      "name": "benz",
      "details": [{
        "name": "C1",
        "year": [{
            "name": "1850",
            "errs": [{
                "user": "model-A",
                "text": "error text on model-H"
              },
              {
                "user": "model-C",
                "text": "error text on model-C"
              }
            ]
          },
          {
            "name": "1820",
            "errs": [{
              "user": "model-C",
              "text": "error text on model-C"
            }]
          }
        ]
      }]
    },
    {
      "name": "vw",
      "details": [{
          "name": "A1",
          "year": [{
              "name": "1860",
              "errs": []
            },
            {
              "name": "1870",
              "errs": [{
                "user": "model-A",
                "text": "error text on model-H"
              }]
            }
          ]
        },
        {
          "name": "A2",
          "year": [{
              "name": "1910",
              "errs": []
            },
            {
              "name": "1950",
              "errs": [{
                "user": "model-A",
                "text": "error text on model-H"
              }]
            }
          ]
        }
      ]
    }
  ]
};

data.car.forEach(function(car, i) {
  car.details.forEach(function(detail, j) {
    detail.year.forEach(function(year, k) {
      year.errs.forEach(function(element, l) {
        if (!processedJSON[element.user]) {
          processedJSON[element.user] = {};
        }
        if (!processedJSON[element.user][car.name]) {
          processedJSON[element.user][car.name] = [];
        }
        if (processedJSON[element.user][car.name].indexOf(detail.name) == -1) {
          processedJSON[element.user][car.name].push(detail.name);
        }
      });
    });
  });
});

console.log(processedJSON);

答案 1 :(得分:0)

您可以使用array#reduce多个array#forEach来构建数据,然后在此结果中使用array#mapObject.keys()来获取最终格式。



const data = { "car": [ { "name": "benz", "details": [ { "name": "C1", "year": [ { "name": "1850", "errs": [ { "user": "model-A", "text": "error text on model-H" }, { "user": "model-C", "text": "error text on model-C" } ] }, { "name": "1820", "errs": [ { "user": "model-C","text": "error text on model-C" } ] } ] } ] }, { "name": "vw", "details": [ { "name": "A1", "year": [ { "name": "1860", "errs": [] }, { "name": "1870", "errs": [ { "user": "model-A", "text": "error text on model-H" } ] } ] }, { "name": "A2", "year": [{ "name": "1910", "errs": [] }, { "name": "1950", "errs": [ { "user": "model-A", "text": "error text on model-H" } ] } ] } ] } ] },
    result = data.car.reduce((r, {name, details}) => {
      details.forEach(o1 => {
        o1.year.forEach(o2 => {
          o2.errs.forEach(({user, text}) => {
              r[user] = r[user] || {};
              r[user][name] = r[user][name] || [];
              if(!r[user][name].includes(o1.name))
                r[user][name].push(o1.name);
          });
        });
      });
      return r;
    },{});
const output = Object.keys(result).map(k => ({label : k, children : Object.keys(result[k]).map(key => ({label: key, children : result[k][key].map(([label]) => ({label}) ) }) ) }) );
console.log(output);