JSON数组到数组的树结构JSON

时间:2019-01-20 07:59:47

标签: javascript arrays json treemap

我想编写一个函数,该函数可以将JSON数组转换为数组的树结构JSON。

我有这样的JSON数组:

$str="<div class='w3-container'><table class=w3-table-all w3-hoverable><caption>Personnes</caption><thead><TR class='w3-light-grey'><TH>Id</TH><TH>Prenom</TH><TH>Nom</TH><TH>Naiss</TH><TH>EMAIL</TH><TH>Statut</TH><TH>Suppr</TH><TH>maj</TH></TR></thead></table>";
$req="SELECT * FROM personnes ORDER BY id_personne ASC;";
$result=mysqli_query($cnx,$req); if(!$result) $msg="requete invalide : ".mysqli_error();
//$result=mysqli_query($cnx,$req); $msg="requete invalide : ".mysqli_error(); $msg=$req;
else{
    foreach ($result as $ligne) {
    $str.="<FORM METHOD='POST' ACTION=''><TABLE><TR>";
        $prenom=$ligne["prenom"];
        $nom=$ligne["nom"];
        $id_personne=$ligne["id_personne"];
        $ddn=$ligne["annee_naissance"];
        $email=$ligne["email"];
        $statut=$ligne["statut"];
        $str.="<TD><input type=hidden name=id_personne value='$id_personne'></TD>";
        $str.="<TR><TD>".$id_personne."</TD>";
        $str.="<TD><input class='w3-input' type=text name='prenom' value=$prenom></TD><TD><input class='w3-input' type=text name='nom' value=$nom></TD><TD><input class='w3-input' type=date name='annee_naissance' value=$ddn></TD><TD><input type=email name='email' value=$email></TD><TD><input type=text name='statut' value=$statut></TD>";
        $str.="<TD><input class='w3-input' type=button onclick=confsuppr($id_personne,\"$nom\"); value=Suppr></TD>";
        $str.="<TD><input class='w3-input' type=submit NAME=maj value=maj /><input type=hidden name=id_personne value=$ligne[id_personne] />  </TD></TR>";
        $str.="</TABLE></FORM>";
    }
    }    
$str.="</div>"; echo $str;?>

我期望这样的输出:

    var rawData = [{
    "dimension": ["a", "c", "f"],
    "metric": [26]
}, {
    "dimension": ["a", "b", "e"],
    "metric": [12]
}, {
    "dimension": ["a", "d", "e"],
    "metric": [7]
}, {
    "dimension": ["a", "b", "f"],
    "metric": [5]
}, {
    "dimension": ["a", "c", "e"],
    "metric": [2]
}, {
    "dimension": ["a", "d", "f"],
    "metric": [1]
}, {
    "dimension": ["a", "k", ""],
    "metric": [2]
},{
    "dimension": ["b", "c", "d"],
    "metric": [2]
}];

请给我一个小的查询。我认为我们不需要更多详细信息。 如果您有其他意见,请随时发表评论。

编辑: 为了使问题更易于理解。

编辑我的代码

output:
{
    name: 'start',
    children: [{
            name: 'a',
            children: [{
                    name: 'c',
                    children: [{
                        name: 'f',
                        value: 26
                    }, {
                        name: 'e',
                        value: 2
                    }]
                },
                {
                    name: 'b',
                    children: [{
                        name: 'e',
                        value: 12
                    }, {
                        name: 'f',
                        value: 5
                    }]
                },
                {
                    name: 'd',
                    children: [{
                        name: 'e',
                        value: 7
                    }, {
                        name: 'f',
                        value: 1
                    }]
                },
                {
                    name: 'k',
                    value: 2
                }
            ]
        },
        {
            name: 'b',
            children: [{
                name: 'c',
                children: [{
                    name: 'd',
                    value: 2
                }]
            }]
        }
    ]
}

1 个答案:

答案 0 :(得分:0)

您可以采用嵌套循环方法,通过迭代rawDatadimention数组,同时为最终对象保存最后一项,并减少其他给定名称,直到找到最终子数组为止。

在内部lopp中,将查找具有相同名称的子代,如果未找到,则会生成并插入新的数据集。

对childrrem使用外部检查有助于缩短路径,而没有子属性。

var rawData = [{ dimension: ["a", "c", "f"], metric: [26] }, { dimension: ["a", "b", "e"], metric: [12] }, { dimension: ["a", "d", "e"], metric: [7] }, { dimension: ["a", "b", "f"], metric: [5] }, { dimension: ["a", "c", "e"], metric: [2] }, { dimension: ["a", "d", "f"], metric: [1] }, { dimension: ["a", "k", ""], metric: [2] }, { dimension: ["b", "c", "d"], metric: [2] }],
    result = { name: "start", children: [] };

rawData.forEach(({ dimension: path, metric: [value] }) => {
    while (!path[path.length - 1]) path.pop(); // remove falsy values from end
    var name = path.pop();
    path
        .reduce((result, name) => {
            var temp = result.find(o => o.name === name);
            if (!temp) {
                result.push(temp = { name });
            }
            temp.children = temp.children || [];
            return temp.children;
        }, result.children)
        .push({ name, value });
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }