最快的方法来平展/不扁平嵌套的JSON对象我将一些代码组合在一起,将复杂/嵌套的JSON对象扁平化和非扁平化。它可以工作,但速度有点慢(触发“长脚本”警告)。为了我想要的扁平的名字“。作为数组的分隔符和[索引]。例子:un-flattened | flattened---------------------------{foo:{bar:false}} => {"foo.bar":false}{a:[{b:["c","d"]}]} => {"a[0].b[0]":"c"
,"a[0].b[1]":"d"}[1,[2,[3,4],5],6] => {"[0]":1,"[1].[0]":2,"[1].[1].[0]":3,"[1].[1].[1]":4,"[1].[2]":5,"[2]":6}我创建了一个基准测试,~模拟我的用例。http://jsfiddle.net/WSzec/获取嵌套的JSON对象把它压平查看它,并可能修改它时,扁平。把它放回原来要运走的嵌套格式我想要更快的代码:为了澄清,完成JSFiddle基准测试的代码(http://jsfiddle.net/WSzec/)在IE9+、FF 24+和Chrome 29+中显著加快(~20%+将很好)。下面是相关的JavaScript代码:当前速度最快:http://jsfiddle.net/WSzec/6/JSON.unflatten = function(data) {
"use strict";
if (Object(data) !== data || Array.isArray(data))
return data;
var result = {}, cur, prop, idx, last, temp;
for(var p in data) {
cur = result, prop = "", last = 0;
do {
idx = p.indexOf(".", last);
temp = p.substring(last, idx !== -1 ? idx : undefined);
cur = cur[prop] || (cur[prop] = (!isNaN(parseInt(temp)) ? [] : {}));
prop = temp;
last = idx + 1;
} while(idx >= 0);
cur[prop] = data[p];
}
return result[""];}JSON.flatten = function(data) {
var result = {};
function recurse (cur, prop) {
if (Object(cur) !== cur) {
result[prop] = cur;
} else if (Array.isArray(cur)) {
for(var i=0, l=cur.length; i<l; i++)
recurse(cur[i], prop ? prop+"."+i : ""+i);
if (l == 0)
result[prop] = [];
} else {
var isEmpty = true;
for (var p in cur) {
isEmpty = false;
recurse(cur[p], prop ? prop+"."+p : p);
}
if (isEmpty)
result[prop] = {};
}
}
recurse(data, "");
return result;}
添加回答
举报
0/150
提交
取消