I have been working on a way to generate a array from a schema. I am almost there I am getting the strings pushed to the array but on when it iterates over the next field it initialises the array again and I am unsure of how to fix it.
I have included a sandbox that has the issue. https://codesandbox.io/s/rough-architecture-i94ph?file=/src/App.js
the output I want should be [contractorName, agencyName]
currently it is outputting
log1 [contractorName]
log2 [agencyName]
log3 []
Any help would be greatly appreciated.
CodePudding user response:
try this
export const generateWatchedFields = (schema) => {
const watchingArray = [];
function iterates(schema){
Object.values(schema).map((propertySchema) => {
if (propertySchema.properties) {
iterates(propertySchema.properties);
} else if (propertySchema.dependencies) {
const push = propertySchema.dependencies.watching;
watchingArray.push(push);
} else {
console.log(watchingArray);
}
});
console.log(watchingArray);
}
iterates(schema)
return watchingArray;
};
I'm not entirely sure if this is what you're looking for but it returns ["contractorName", "agencyName"]
CodePudding user response:
Looks like the problem is, that you declare your watchingArray
in generateWatchedFields
everytime you call generateWatchedFields
.
export const generateWatchedFields = (schema) => {
const watchingArray = []; // New array on every call
Object.values(schema).map((propertySchema) => {
if (propertySchema.properties) {
return generateWatchedFields(propertySchema.properties);
} else if (propertySchema.dependencies) {
const push = propertySchema.dependencies.watching;
return watchingArray.push(push);
} else {
console.log(watchingArray);
}
});
console.log(watchingArray);
return watchingArray;
};
So you just need to declare it outside of this context, like this:
var watchingArray = [];
export const generateWatchedFields = (schema) => {
Object.values(schema).map((propertySchema) => {
if (propertySchema.properties) {
return generateWatchedFields(propertySchema.properties);
} else if (propertySchema.dependencies) {
const push = propertySchema.dependencies.watching;
return watchingArray.push(push);
} else {
console.log(watchingArray);
}
});
console.log(watchingArray);
return watchingArray;
};