为什么箭头函数 return 未定义

why arrow function return undefined

我正在编写一个简单循环遍历 Json 模式的函数。假设我们有一个简单的 json 模式,例如:

    var foo = {
  "description": "A car  schema",
  "type": "object",
  "properties": {
    "_id": {
      "type": "string"
    },
    "_rev": {
      "type": "string"
    },
    "sources": {
      "type": "object",
      "properties": {
        "mam": {
          "type": "object",
          "properties": {
            "source_id": {
              "type": [ "integer", "null" ]
            },
            "SOR": {
              "type": ["boolean","null"]
            }
          }
        },
        "sas": {
          "type": "object",
          "properties": {
            "source_id": {
              "type": "string"
            },
            "SOR": {
              "type": ["boolean","null"]
            },
            "CAR": {
              "type": ["object","null"]
            }
          }
        }
      }
    }
  }
}

我们正在尝试从中收集关键对象的类型。这是 CAR 类型的函数搜索应该 return => "object"

parseObjectProperties = (obj)=> {
  for (var k in obj) {
    if(k === "CAR"){
     console.log(_.values(obj[k])[0][0]) // When I do a console log like this prin the object value
     return  _.values(obj[k])[0][0] // but in return i get undefined 
      }
    if ( _.isObject( obj[k]) && !_.isNil(obj[k])) {
    return  parseObjectProperties(obj[k])
    } 
  }
}


parseObjectProperties(foo);

当我 运行 它时,内部 console.log(_.values(obj[k])[0][0]) 显示正确的值:对象

但是如果我运行它

console.log(parseObjectProperties(foo));

我明白了

undefined

为什么功能不正确return输入正确的值=>"object"?

谢谢!

我刚刚重写了这篇文章,因为我不明白你使用的逻辑。这是否解决了您的问题?

仅供参考,您的对象 CAR 有一个名为 type 的 属性,其值是一个包含 2 个值的数组,"object" 和 "null",因此您想使用 obj[k].type[0] 如果你想得到 "object" 作为结果。

const parseObjectProperties = (obj) => {
  var result = null;
  for (var k in obj)
    if (k == "CAR") return obj[k].type[0];
    else if (obj[k] instanceof Object) 
      result = parseObjectProperties(obj[k]);
  return result;
}


var foo = {
  "description": "A car  schema",
  "type": "object",
  "properties": {
    "_id": {
      "type": "string"
    },
    "_rev": {
      "type": "string"
    },
    "sources": {
      "type": "object",
      "properties": {
        "mam": {
          "type": "object",
          "properties": {
            "source_id": {
              "type": ["integer", "null"]
            },
            "SOR": {
              "type": ["boolean", "null"]
            }
          }
        },
        "sas": {
          "type": "object",
          "properties": {
            "source_id": {
              "type": "string"
            },
            "SOR": {
              "type": ["boolean", "null"]
            },
            "CAR": {
              "type": ["object", "null"]
            }
          }
        }
      }
    }
  }
}

console.log(parseObjectProperties(foo));