0

给定一个字符串数组的数组,如下所示:

incoming = [["1","A","C","3"],
            ["2","A","C","1"],
            ["1","B","D","3"],
            ["2","B","D","4"],
            ["2","B","D","5"]];

如何将其转换为这样的 json 对象:

[
  { "1": [
         { "A": [
                 { "C": ["3"] 
                 }
              ]
         },
         { "B": [
                 { "D": ["3"] 
                 }
              ]
         }
       ]
   },
   { "2": [
         { "A": [
                 { "C": ["1"] 
                 }
              ]
         },
         { "B": [
                 { "D": ["4","5"] 
                 }
              ]
         }
       ]
   }
]

我查看了相关问题的几个答案,但无法弄清楚如何将它们映射到这个特定要求。

在 PHP 中,这将非常简单。

foreach (incoming AS inc)
{
    output[inc[0]][inc[1]][inc[2]][inc[3]] = "x"; 
}

谢谢!

4

2 回答 2

0

您的问题表述得不是很好。也许你想要:

var incoming = [['1', 'A', 'C', '3'], ['2', 'A', 'C', '1'], ['1', 'B', 'D', '3'], ['2', 'B', 'D', '4'], ['2', 'B', 'D', '5']];
var obj = {}, propNames = ['prop1', 'prop2', 'prop3', 'prop4', 'prop5'];
for(var i in incoming){
   obj[propNames[i]] = incoming[i];
}

但是请注意,您不能在早期版本的 IE上运行for in循环。如果您根据该代码获取信息,则可能如下所示:.getElementsByTagName().getElementsByName()

var incoming = [['1', 'A', 'C', '3'], ['2', 'A', 'C', '1'], ['1', 'B', 'D', '3'], ['2', 'B', 'D', '4'], ['2', 'B', 'D', '5']];
var obj = {}, propNames = ['prop1', 'prop2', 'prop3', 'prop4', 'prop5'];
for(var i=0,l=incoming.length; i>l; i++){
    obj[propNames[i]] = incoming[i];
}

请注意,arrayName[increment]objectName[property]在 JavaScript 中获取与$valuePHP 中的变量等效的值foreach($whatever as $value)。当然,我所做的只是将每个数组分配给 obj.prop1 等等。它不会创建您显示的结构。这将要求您的 JavaScript 对象的每个属性都具有不同的名称。

要复制底层 PHP 代码,在 JavaScript 中可能如下所示:

var output = {};
for(var i in incoming){
  var inc = incoming[i];
  output[inc[0]][inc[1]][inc[2]][inc[3]] = 'x';
}

请注意,我上面的最后一段代码和你的最后一段代码没有意义。这在 PHP 或 JavaScript 中不起作用。

于 2013-06-20T01:11:51.767 回答
0

分成两步,

第一步,将数组转换成Object

var incoming = [["1","A","C","3"], ["2","A","C","1"], ["1","B","D","3"],
                ["2","B","D","4"], ["2","B","D","5"]];

var i, j, o = {}, c, k;

for (i = 0; i < incoming.length; ++i) {
    c = o;
    for (j = 0; j < incoming[i].length; ++j) {
        k = incoming[i][j];
        if (!c[k]) c[k] = {};
        c = c[k];
    }
}

现在o看起来像你想要的,只是它没有按照你的意愿排列,所以需要更多的工作。
第二步,通过keys=>arrays重新创建Object树,使用递归

function recurseKeys(o) {
    var arr = [],
        k = Object.getOwnPropertyNames(o),
        i, c;
    for (i = 0; i < k.length; ++i) {
        if (Object.getOwnPropertyNames(o[k[i]]).length)
            c = {}, c[k[i]] = recurseKeys(o[k[i]]);
        else
            c = k[i];
        arr.push(c);
    }
    return arr;
}

o = recurseKeys(o);

现在o应该有你想要的结构,所以 JSON 化它

JSON.stringify(o);
// "[{"1":[{"A":[{"C":["3"]}]},{"B":[{"D":["3"]}]}]},{"2":[{"A":[{"C":["1"]}]},{"B":[{"D":["4","5"]}]}]}]"
于 2013-06-20T01:40:51.947 回答