给出一个像这样的字符串数组的数组:
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";
}
谢谢!
答案 0 :(得分: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值等同于PHP $value
中的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中不起作用。
答案 1 :(得分:0)
将其分解为两个步骤,
步骤1,将数组转换为 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
看起来像你想要的,除了它没有按照你的意愿排列,所以需要更多的工作。
步骤2,使用递归
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-ify it
JSON.stringify(o);
// "[{"1":[{"A":[{"C":["3"]}]},{"B":[{"D":["3"]}]}]},{"2":[{"A":[{"C":["1"]}]},{"B":[{"D":["4","5"]}]}]}]"