对象数组对象的对象

时间:2016-07-29 14:13:11

标签: javascript node.js

由于原因,我宁愿不进入在Java应用程序内部运行的Java Nashorn的js脚本的结构现在具有不同的结构。因为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 个答案:

答案 0 :(得分: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/

相关问题