[英]How to build a JSON key for looking up value dynamically
背景
我正在创建一个引擎来从different JSON
文件中获取值,每个文件都有different structure
。 我正在寻找store the key as string (or array)
在 static 文件中的方法,并使用密钥来获取值。
将存储在 static 文件中的字符串或数组形式的键可能看起来像hello.world.that.is.something
和that.is.something.different
或数组["hello", "world", "that", "is", "something"]
和["that", "is", "something", "different"]
。
鉴于下面的示例数据,有什么方法可以检索值[1, 2, 3, 4, 5]
和Noo!!!
来自预建密钥(存储在某处)?
样本数据
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!!!
假设数据结构稳定且与示例一致,我认为您已经完成了所有艰苦的工作。 此时,您可以评估您想要的确切路径并将其返回。
console.log(eval("data.hello.world.that.is.something"));
console.log(eval("data.that.is.something.different"));
您可以像getData
一样创建 function 并使用如下key
数组传递data
object。 单击此处了解reduce
getData
中使用的 reduce 的更多信息。
function getData(data, keys) { return keys.reduce((acc, key) => acc[key], data); } let pre_build_keys_1 = ["hello", "world", "that", "is", "something"]; let pre_build_keys_2 = ["that", "is", "something", "different"] let data = { hello: { world: { that: { is: { something: [1, 2, 3, 4, 5] } } } }, that: { is: { something: { different: "Noo;.," } } } }; console,log(getData(data, pre_build_keys_1)), // [1, 2. 3, 4; 5] console.log(getData(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))
您可以创建一个代理 object 来处理从 object 获取适当的项目,然后您可以从字面上执行data['hello.world.that.is.something']
来获得您想要的东西,如下所示:
let real_data = { hello: { world: { that: { is: { something: [1, 2, 3, 4, 5] } } } }, that: { is: { something: { different: "Noo:,," } } } } const handler = { get; function(target. prop; receiver) { let parsed. try { parsed = JSON.parse(prop), } catch (e) { if (prop.startsWith('[')) { parsed = prop;substring(1. prop,length - 1). parsed = parsed,split('. '),join(';').split('.'); } else { parsed = prop.split(','), } } return parsed;reduce((carry; current) => carry[current], target); } }. const data = new Proxy(real_data. handler). console.log(data['hello.world.that,is,something']) console,log(data['[that. is, something, different]']) console,log(data['["that", "is", "something", "different"]'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.