更改深层嵌套对象的JSON结构

时间:2018-10-10 10:37:51

标签: javascript json recursion javascript-objects traversal

我正在尝试将深层嵌套的JSON对象从一种结构更改为另一种结构。 为了能够以正确的格式使用它,以便与名为jQuery Nestable的库一起使用。

这是我的原始格式:

->get()

与库一起使用的所需JSON格式是这样:

  {
      "scanned": {
          "a3": {
              "value": 906
          },
          "value": 23667
      },
      "total": {
          "printed": {
              "black": {
                  "value": 44
              },
              "color": {
                  "value": 57
              },
              "value": 101
          },
          "value": 101
      }
  }

我试图用递归函数遍历那棵树,但到目前为止还没有达到预期的结果:

[{
    "id": "scanned: 23667",
    "children": [{
        "id": "a3: 906"
    }]
}, {
    "id": "total: 101",
    "children": [{
        "id": "printed: 101",
        "children": [{
            "id": "black: 44"
        }, {
            "id": "color: 57"
        }]
    }]
}]

有人可以给我提供一个可行的例子吗?

2 个答案:

答案 0 :(得分:1)

这有效:

var a =  {"total":{"printed":{"black":{"value":44},"color":{"value":57},"value":101},"value":101}};
  
function changeFormat(currObj, parent) {
  if (typeof (parent) == 'object') {
    Object.keys(parent).map((key) => {
      if (key != 'value') {
        var obj = {}
        obj['id'] = key + ": " + parent[key].value


        if (typeof (parent[key]) == 'object' && Object.keys(parent[key]).length > 1) {
          obj['children'] = [];
          changeFormat(obj['children'], parent[key])
        }
        currObj.push(obj);
      }
    })
  }
}

var result = [];

changeFormat(result, a);
console.log(result);

答案 1 :(得分:0)

尝试关注

let obj = {"total":{"printed":{"black":{"value":44},"color":{"value":57},"value":101},"value":101}};
  
/* Rest parameters where other other keys are collected in rest object */
function processObj({value, ...rest}, r=[]) {
  /* Iterate over each key/value pair in rest object */
  Object.entries(rest).forEach(([k,v], i) => {
    if(Array.isArray(r)) { // For first level items
      r[i] = {"id" : `${k}: ${v.value}`};
      processObj(v, r[i]);
    } else { // For child nodes
      r.children = r.children || [];
      r.children[i] = {"id" : `${k}: ${v.value}`};
      processObj(v, r.children[i]);

    }
  });
  return r;
}
  
console.log(processObj(obj))