节点js递归函数中的for / in函数完成时如何返回

时间:2018-12-19 12:19:09

标签: node.js json recursion

我正在像下面那样在node.js中迭代嵌套的json,并希望获取类型为abc的所有attrList,并创建另一个json。

我能够提取所需的数据并创建输出json。

但是我应该如何返回最终的输出数组?我无法确定退出/返回条件。我是Node JS的新手,仍在学习。有人可以帮忙吗?

 function recursion(input, output) {
    if (input["Type"] == "abc") {
        let attrlist = {};
          for (let i = 0; i < input["atrrlist"].length; i++) {

            attrlist[input["atrrlist"][i]["name"]] = input["atrrlist"][i]["val"];
        }
        if (input["atrrlist"].length > 0) {
            output[input["a"]] = attrlist;
        }
      }
    for (let obj in input) {
        if (typeof input[obj] == "object" && input[obj] !== null) {
             recursion(input[obj], output);
        }
    }
}

我这样称呼。

let output={};
recursion(input, output)

输入json如下:

 {
  "a": "val",
 "b": "val2",
 "Type": "abc",
  atrrlist": [{
    "name": "vbv",
    "val": "vbv"
}],
"child": [{
    "a": "val",
    "b2": "val2",
    "Type": "abc",
    "atrrlist": [{
        "name": "vbv",
        "val": "vbv"
    }],
    "child": [{
        "a": "val",
        "b2": "val2",
        "Type": "abc",
       "atrrlist": [{
            "name": "vbv",
            "val": "vbv"
        }],
        "child": [{
            "a": "val",
            "b2": "val2",
            "Type": "xyz",
            "atrrlist": [{
                "name": "vbv",
                "val": "vbv"
            }]

        }]

    }]
}]

 }

1 个答案:

答案 0 :(得分:1)

您没有指定期望的输出结构,只是它是一个数组。

我建议不要将output作为参数传递,而应使其成为recursion函数的 return 值。 代码中的主要问题是您没有将递归结果连接到“当前”结果。编写“我应如何返回最终输出数组?” 时,您唯一定义output的地方不是数组。因此,将其定义为数组并将结果(递归结果)推入该数组。

function recursion(input) {
    const output = [];
    if (input.Type === "abc") {
        const attrlist = {};
        for (const {name, val} of input.atrrlist) {
            attrlist[name] = val;
        }
        if (input.atrrlist.length > 0) {
            output.push({ [input.a]: attrlist });
        }
    }
    for (const obj of Object.values(input)) {
        if (Object(obj) === obj) {
            output.push(...recursion(obj));
        }
    }
    return output;
}

// Sample input:
const input = {"a": "val","b": "val2","Type": "abc","atrrlist": [{"name": "category","val": "furniture"}],"child": [{"a": "val","b2": "val2","Type": "abc","atrrlist": [{"name": "product","val": "chair"}],"child": [{"a": "val","b2": "val2","Type": "abc","atrrlist": [{"name": "color","val": "blue"}],"child": [{"a": "val","b2": "val2","Type": "xyz","atrrlist": [{"name": "vbv","val": "vbv"}]}]}]}]};

console.log(recursion(input));