regex 在JavaScript中从JSON中提取子集

bvuwiixz  于 2023-10-22  发布在  Java
关注(0)|答案(1)|浏览(121)

我想在JavaScript中基于输入从主要JSON批量数据中提取JSON条目。主JSON数据中的每个条目都有自己的唯一ID,但过滤器应该基于文本标识符而不是ID。例如,我想检索包含单词burgBurgBURGbUrg等)或任何其他给定品种的所有条目。当然,这也适用于其他搜索词。我没有JavaScript技能来做这件事。
在下面给出的数据中,这应该返回3个结果。显然,结果应该是完全相同的JSON格式。
JSON示例:

{"type":"FeatureCollection","features":[
    {"id":1,"text":"Cape Town"},
    {"id":2,"text":"Kimberley"},
    {"id":3,"text":"Beaufort West"},
    {"id":4,"text":"Johannesburg Park"},
    {"id":5,"text":"Germiston"},
    {"id":6,"text":"Pietermaritzburg"},
    {"id":7,"text":"Durban"},
    {"id":8,"text":"Bellville"},
    {"id":9,"text":"Wellington"},
    {"id":10,"text":"Huguenot"},
    {"id":11,"text":"Worcester"},
    {"id":12,"text":"Matjiesfontein"},
    {"id":13,"text":"Laingsburg"},
    {"id":14,"text":"Prince Albert"},
    {"id":15,"text":"Hutchinson"},
    {"id":16,"text":"De Aar"},
    {"id":17,"text":"Warrenton"}
]}
jgovgodb

jgovgodb1#

请勿使用JavaScript。请改用SQL及其LIKE运算符。

But if you insist on using JavaScript for this…
就像HTML一样,正则表达式由于序列化而无法完全解析JSON。
JSON.parse之后的过滤非常容易;可以使用Array.prototype.filter()方法:

var s = '{"type":"FeatureCollection","features":[{"id":1,"text":"Cape Town"},{"id":2,"text":"Kimberley"},{"id":3,"text":"Beaufort West"},{"id":4,"text":"Johannesburg Park"},{"id":5,"text":"Germiston"},{"id":6,"text":"Pietermaritzburg"},{"id":7,"text":"Durban"},{"id":8,"text":"Bellville"},{"id":9,"text":"Wellington"},{"id":10,"text":"Huguenot"},{"id":11,"text":"Worcester"},{"id":12,"text":"Matjiesfontein"},{"id":13,"text":"Laingsburg"},{"id":14,"text":"Prince Albert"},{"id":15,"text":"Hutchinson"},{"id":16,"text":"De Aar"},{"id":17,"text":"Warrenton"}]}';
var input = "burg";
var o = JSON.parse(s);
o.features = o.features.filter(e => RegExp(input, 'i').test(e.text));
console.log(JSON.stringify(o));

相关问题