在javascript中从json中提取子集

时间:2017-11-07 19:51:24

标签: javascript json regex subset

我想在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"}]}

1 个答案:

答案 0 :(得分:2)

不要使用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));