使用JQuery将定界字符串转换为分层JSON [英] Convert delimited string into hierarchical JSON with JQuery

查看:151
本文介绍了使用JQuery将定界字符串转换为分层JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串数组,这些字符串通过用短划线分隔来描述父/子关系.因此,如果鲍勃的老板是吉姆而吉姆的老板是弗雷德,则鲍勃在数组中的条目将是弗雷德-吉姆-鲍勃",而吉姆的条目将是弗雷德-吉姆". 我没有能力更改数据输入的方式,因此我一直在寻求帮助,以将这些值转换为类似于以下内容的JSON的最佳方法:

I have an array of strings that describe the parent/child relationship by being delimited with dashes. So, if Bob's boss was Jim and Jim's boss was Fred, Bob's entry in the array would be "Fred-Jim-Bob" and Jim's entry would be "Fred-Jim." I don't have the ability to change the way the data is coming in so I was looking for help as far as the best way of turning these values into JSON similar to this:

{
    "name": "Fred",
    "children": {
        "name": "Jim",
        "children": {
            "name": "Bob"
        }
    }
}

任何帮助将不胜感激. 谢谢.

Any help would be greatly appreciated. Thanks.

推荐答案

var input = ["Fred-Jim-Bob", "Fred-Jim", "Fred-Thomas-Rob", "Fred"];
var output = [];
for (var i = 0; i < input.length; i++) {
    var chain = input[i].split("-");
    var currentNode = output;
    for (var j = 0; j < chain.length; j++) {
        var wantedNode = chain[j];
        var lastNode = currentNode;
        for (var k = 0; k < currentNode.length; k++) {
            if (currentNode[k].name == wantedNode) {
                currentNode = currentNode[k].children;
                break;
            }
        }
        // If we couldn't find an item in this list of children
        // that has the right name, create one:
        if (lastNode == currentNode) {
            var newNode = currentNode[k] = {name: wantedNode, children: []};
            currentNode = newNode.children;
        }
    }
}

将JSONify输出为:

output JSONifies as:

[{
    "name": "Fred",
    "children": [{
        "name": "Jim",
        "children": [{
            "name": "Bob",
            "children": []
        }]
    }, {
        "name": "Thomas",
        "children": [{
            "name": "Rob",
            "children": []
        }]
    }]
}]

这篇关于使用JQuery将定界字符串转换为分层JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆