背景
我正在创建一个引擎来从 different JSON
中获取值文件,每个文件都有 different structure
。我正在寻找store the key as string (or array)
的方法在静态文件中,并使用键来获取值。
要存储在静态文件中的字符串或数组形式的键可能类似于 hello.world.that.is.something
和that.is.something.different
或数组 ["hello", "world", "that", "is", "something"]
和["that", "is", "something", "different"]
.
鉴于下面的示例数据,有什么方法可以检索值 [1, 2, 3, 4, 5]
和Noo!!!
来自预构建 key (存储在某处)?
示例数据
let data = {
hello: {
world: {
that: {
is: {
something: [1, 2, 3, 4, 5]
}
}
}
},
that: {
is: {
something: {
different: "Noo!!!"
}
}
}
}
预期数据
data[pre_build_keys_1] // [1, 2, 3, 4, 5]
data[pre_build_keys_2] // Noo!!!
最佳答案
您可以使用 eval()
来评估字符串并将其视为节点/变量,假设您已声明了与评估的字符串等效的变量名称。
let data = {
hello: {
world: {
that: {
is: {
something: [1, 2, 3, 4, 5]
}
}
}
},
that: {
is: {
something: {
different: "Noo!!!"
}
}
}
}
let pre_build_keys_1 = "data.hello.world.that.is.something"
let pre_build_keys_2 = "data.that.is.something.different"
console.log(eval(pre_build_keys_1))
console.log(eval(pre_build_keys_2))
关于javascript - 如何构建 JSON 键以动态查找值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63295690/