我一直在研究一种从模式生成数组的方法。我几乎在那里,我得到的字符串推到数组,但当它迭代到下一个字段,它再次初始化数组,我不确定如何修复它。
我已经包含了一个有这个问题的沙箱。https://codesandbox.io/s/rough-architecture-i94ph?file=/src/App.js
我想要的输出应该是[contractorName, agencyName]
当前正在输出log1 [contractorName]
log2 [agencyName]
log3 []
任何帮助都将是非常感激的。
看起来问题是,每次调用generateWatchedFields
时,您都在generateWatchedFields
中声明watchingArray
。
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;
};
所以你只需要在这个上下文中声明它,像这样:
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;
};
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;
};
我不完全确定这是否是你要找的,但是它返回["contractorName", "agencyName"]