2016-07-29 118 views
-2

由于原因,我不想深入研究在Java应用程序中运行Java jash脚本的结构,现在它具有不同的结构。由于Java团队无法将之前已经存在的对象数组转换成对象,因此它不会成为对象的对象。这里的复杂性在于它的嵌套非常像5-6层。与其使用我为几个应用程序进行转换的直接方法,找到一种获得递归解决方案的方法非常好。对象对象数组对象

这里的结构是什么样的解决方案应该是不可知的键名:

{ 
    "abc": { 
    "items": { 
    "0": { 
     "cde": "123456", 
     "fgh":{ 
      "0": {"ijk":"987654"} 
     } 
    }, 

    .... 
It goes on and on. 
} 

} 
} 

对不起,我不漂亮打印JSON

产量预计:

{ 
    "abc": { 
    "items": [ 
    { 
     "cde": "123456", 
     "fgh":[{"ijk":"987654"}], 

    .... 
It goes on and on. 
    } 

] 
} 

我已经能够使用下划线的_.toArray和我自己的函数,因为下划线的解决方案是完美的克拉。

有没有建议吗?任何解决方案?强调?

+1

它根本不清楚你想要什么输出实际样子。但它看起来像一个嵌套数组的JSON表示,看起来好像不应该太难以至少开始 - 到目前为止你有什么,以及它有什么问题? –

+0

我的歉意。具有“项目”的部分:{“0”:{...}}应该是一个数组,例如“items”:[{“cde”:“123456”,...}] – nickmenow

回答

1

这会帮助你入门..请阅读我的意见,以提高解决方案

//test object 
var json = { 
    "abc": { 
     "items": { 
      "0": { 
       "cde": "123456", 
       "fgh":{ 
        "0": {"ijk":"987654"} 
       } 
      }, 
     }, 
    }, 
}; 

//check array: this code should be customized to your needs- I only check for numbers here 
var isArray = function (obj) { 
    if (typeof obj !== 'object') 
     throw new Error('invalid argument'); 
    for (var m in obj) 
     if (obj.hasOwnProperty(m) && !/^\d+$/.test(m)) //test if key is numeric 
     return false; 

    return true; 
} 

//recursive parse-function 
var parse = function (obj, node) { 
    if (typeof obj !== 'object') 
     return obj; //break condition for non objects 

    if (isArray(obj)) { 
     node = node || []; 
     for (var m in obj) 
      node.push(parse(obj[m])); 
    } 
    else { 
     node = node || {}; 
     for (var m in obj) 
      node[m] = parse(obj[m]); 
    } 

    return node; 
} 

//run 
var newObj = parse(json); 
console.log(JSON.stringify(newObj)); 

的jsfiddle:https://jsfiddle.net/oh4ncbzc/

+0

谢谢。这完全符合我的目的。我从中学到了很多,因为这种方法比我的尝试更简单,更好。 – nickmenow

+0

不客气。 – Wolfgang