将单个 json 拆分为单独的列表

Split individual json to separate list

本文关键字:单独 列表 拆分 单个 json      更新时间:2023-09-26

我有以下嵌套的json列表。我已经实现了loopJson,但是它不是递归的,也不会传递第一个对象列表。如果有人可以建议应该进行递归调用的位置,以便执行递归,那就太好了。

{
"key": "math",
"right": {
    "key": "Math"
},
"left": {
    "key": "A Greek–English Lexicon",
    "right": {
        "key": "A-list"
    },
    "left": {
        "key": "ASCII"
    }
}
}
      var loopJson = function(json){
      if(json.left.key != null){
          that.arrayTest.push({key:json.key,left:json.left.key});
      }
      if(json.right.key != null){
          that.arrayTest.push({key:json.key,right:json.right.key});
      }
  }

目标:遍历每个对象并创建一个对象数组,该数组由具有键("键","右")或("键","左")的对象组成。由于当前的 json 是嵌套的,我想将 json 拆分为一个对象数组。但是,它不会遍历每个对象,因为它不是递归的。我必须找到一种方法来使其递归。

预期输出的示例:

[{key:"math",right:"Math"},{key:"math",left: "A Greek–English Lexicon"},{key: "A Greek–English Lexicon",left:""ASCII},{key: "A Greek–English Lexicon",right:"A-list"}]

var input = {
    "key": "math",
    "right": {
        "key": "Math"
    },
    "left": {
        "key": "A Greek–English Lexicon",
        "right": {
            "key": "A-list"
        },
        "left": {
            "key": "ASCII"
        }
    }
};
var nestedMethod = function(input) {
  var output = [];
  
  if (input.right) {
    output.push({ key: input.key, right: input.right.key });
    output = output.concat(nestedMethod(input.right));
  }
    
  if (input.left) {
    output.push({ key: input.key, left: input.left.key });
    output = output.concat(nestedMethod(input.left));
  }
  
  return output;
}
document.write(JSON.stringify(nestedMethod(input)));

这是一个

具有递归函数和固定属性数组的建议,需要照顾。

var object = {
        "key": "math",
        "right": {
            "key": "Math"
        },
        "left": {
            "key": "A Greek–English Lexicon",
            "right": {
                "key": "A-list"
            },
            "left": {
                "key": "ASCII"
            }
        }
    },
    array = [];
function getParts(object, array) {
    ['right', 'left'].forEach(function (k) {
        var o;
        if (object[k]) {
            o = { key: object.key };
            o[k] = object[k].key;
            array.push(o);
            getParts(object[k], array);
        }
    });
}
getParts(object, array);
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');