I'm writing a function that simply loops through a Json schema. Let us say we have a simple json schema such as:
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"]
}
}
}
}
}
}
}
We're trying to collect the type of the key object from it. Here is function search for CAR type should 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);
When I run it, the inner console.log(_.values(obj[k])[0][0]) shows the correct value: object
but if i run it
console.log(parseObjectProperties(foo));
I get
undefined
Why isn't the function properly returning the correct value => "object"?
Thank you!
I just re-wrote this as I didn't understand the logic you were using. Does this solve your problem?
FYI your object CAR, has a property named type
whose value is an array that contains 2 values, "object" and "null" so you want to use obj[k].type[0]
if you want to get "object" as the result.
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.