javascript - 如何在javascript中对json数据应用递归函数
问题描述
我在 js 中有这样的验证模式
var data = [
{
id: {
label: "",
tests: [
{
name: "required",
params: "",
},
],
},
},
{
name: {
fields: {
firstName: {
label: "",
tests: [
{
name: "required",
params: "",
},
],
},
lastName: {
label: "",
tests: [
{
name: "required",
params: "",
},
],
},
midName: {
label: "",
tests: [],
},
},
tests: [],
},
},
{
email: {
label: "",
tests: [
{
name: "required",
params: "",
},
],
},
},
{
city: {
label: "",
tests: [],
},
},
{
details: {
fields: {
age: {
label: "",
tests: [
{
name: "max",
params: {
max: 18,
},
},
],
},
tests: [],
},
},
},
];
我只想要数组中键的名称,它具有像这个 var selected = [“id”,“name”,“email”] 这样的必填字段。为此,想要创建一个动态函数,例如如果数据具有键:“测试”“必需”,它将返回名称,如果数据具有键:“字段”,它将再次检查“测试”。
解决方案
var data = [
{
id: {
label: "",
tests: [
{
name: "required",
params: "",
},
],
},
},
{
name: {
fields: {
firstName: {
label: "",
tests: [
{
name: "required",
params: "",
},
],
},
lastName: {
label: "",
tests: [
{
name: "required",
params: "",
},
],
},
midName: {
label: "",
tests: [],
},
},
tests: [],
},
},
{
email: {
label: "",
tests: [
{
name: "required",
params: "",
},
],
},
},
{
city: {
label: "",
tests: [],
},
},
{
details: {
fields: {
age: {
label: "",
tests: [
{
name: "max",
params: {
max: 18,
},
},
],
},
tests: [],
},
},
},
]
console.clear()
const keys = data.map(x => recursive(Object.keys(x)[0], x)).filter(x => x !== undefined)
function recursive (name, x) {
for (let key in x) {
if (x[key].tests !== undefined && typeof x[key].tests === "object") {
const find = x[key].tests.find(y => y.name === "required")
if (find) return name
}
if (x[key].fields !== undefined) {
for (let y in x[key].fields) {
if (y !== "tests") {
console.log(y)
const v = recursive(parent, x[key].fields)
if (v !== undefined) return name
}
}
}
}
}
console.log("KEYS", keys)
require
就像您说的那样,如果我们在现场只有一次,则在孩子中进行递归搜索name
。只是您需要记住数据的名称并在最后进行过滤,因为我不返回名称,因此undefined
如果我没有找到这个特定的字符串字段则返回。
推荐阅读
- c - 如何在C中将字符串转换为完整的整数?
- javascript - 如何检查我的计算机上全局安装的 npm 包?
- pandas - 如何计算 Apache Beam 的百分比变化?即pandas.DataFrame.pct_change
- javascript - 如何根据 Reactjs 中的产品数量计算产品总价?
- python - Python sympy:对布尔表达式结果使用 simplfy 和非简化表达式
- javascript - 如何在每次单击 .map 项目列表中的每个项目时呈现不同的数据?
- assembly - 程序集中的 _start 符号可以换成别的词吗?
- python - 使用 pyspark.ml 从 LDA 模型中获取推荐的主题数量
- reactjs - 如何在 Gatsby 和 GraphQL 中正确使用 formatString?
- javascript - 如何仅在javascript中单击按钮时才播放视频