Easiest way to interate over a complex JSON object via Javascript

后端 未结 7 1900
生来不讨喜
生来不讨喜 2020-12-21 07:19

I\'m consuming JSON data that has a bit of a weird structure for example:

{
    \"RESULT\": 
    {
        \"COLUMNS\": [\"ID\",\"name\",\"ENABLED\",\"perms\         


        
7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-21 08:08

    Actually, you could use a combination of Array#map for the array and Array#reduce for the objects with the new properties

    var data = { RESULT: { COLUMNS: ["ID", "name", "ENABLED", "perms", "vcenabled", "vcvalue", "checkenabled", "checkvalue", "indxenabled", "indxvalue"], DATA: [[7, "Site-A", 1, "1,2", 1, 1, 1, 0, 0, 0], [15, "Site-B", 1, "1,2,3,4", 1, 1, 1, 0, 0, 0]] }, ERROR: 0 },
        result = data.RESULT.DATA.map(function (a) {
            return a.reduce(function (o, d, i) {
                o[data.RESULT.COLUMNS[i]] = d;
                return o;
            }, {});
        });
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    With ES6, you could use Object.assign with spread syntax ....

    Object.assign adds properties to the given object and returns this object.

    Spread syntax ... takes an array and insert the elements as parameters to the function.

    var data = { RESULT: { COLUMNS: ["ID", "name", "ENABLED", "perms", "vcenabled", "vcvalue", "checkenabled", "checkvalue", "indxenabled", "indxvalue"], DATA: [[7, "Site-A", 1, "1,2", 1, 1, 1, 0, 0, 0], [15, "Site-B", 1, "1,2,3,4", 1, 1, 1, 0, 0, 0]] }, ERROR: 0 },
        result = data.RESULT.DATA.map(a =>
            Object.assign(...data.RESULT.COLUMNS.map((k, i) => ({ [k]: a[i] }))));
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题