这个Meteor客户端应用程序“主要是smartPhone使用”需要接受用户输入的类型文本形式,并过滤大约500个底层节点的json数据,返回树的分支,其中底部节点文本包含用户输入文本。
{
"people": {
"honour": [
[
"family"
],
[
"friends"
]
],
"respect": [
[
"one another"
]
]
},
"animals": {
"eat": [
[
"row food"
]
]
}
}当用户输入'a‘时,代码需要给出出现这种情况的树:
人民荣誉家庭。
人,尊重,互相尊重
当用户键入'o‘时,输出应该是:
人,尊重,互相尊重。
动物,吃,划食物。
当用户键入“oo”时,输出应该是:
动物,吃,划食物。
当用户键入'f‘时,输出应该是:
人民荣誉家庭。
各位荣誉朋友们。
动物,吃,划食物。
我的选择是:
哪一个最适合快速的结果和易于维护?谢谢
发布于 2016-06-21 04:17:11
我想几个循环会很好。在下面的示例中,当您键入输入时,匹配搜索的结果将被记录到控制台。
$("#search").on("input", function() {
var result = [];
var search = this.value;
if (search.length) {
$.each(data, function(key1, value1) {
//key1: people, animals
$.each(value1, function(key2, value2) {
//key2: honor, respect, eat
$.each(value2, function(i, leaf) {
if (leaf.length && leaf[0].indexOf(search) >= 0) {
//found a match, push it onto the result
var obj = {};
obj[key1] = {};
obj[key1][key2] = leaf;
result.push(obj);
}
});
});
});
}
console.log(result);
});
var data = {
"people": {
"honour": [
[
"family"
],
[
"friends"
]
],
"respect": [
[
"one another"
]
]
},
"animals": {
"eat": [
[
"row food"
]
]
}
};<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="search" />
发布于 2016-06-21 06:42:54
好的,这个问题是我创建一个通用对象方法Object.prototype.paths()来获取对象中所有路径的借口。在对象中有许多值,有许多路径。在不同路径的末尾,某些值可能是相同的。我们将生成一个以原始对象的值作为属性的对象,这些属性的值将是路径。每个值可能有几个路径,因此一个字符串数组,其中每个字符串数组将包含一个指向该值的路径。
因此,一旦我们有了这个工具来映射对象值和路径,就很容易得到结果。
Object.prototype.paths = function(root = [], result = {}) {
var ok = Object.keys(this);
return ok.reduce((res,key) => { var path = root.concat(key);
typeof this[key] === "object" &&
this[key] !== null ? this[key].paths(path,res)
: res[this[key]] == 0 || res[this[key]] ? res[this[key]].push(path)
: res[this[key]] = [path];
return res;
},result);
};
var data = {"people":{"honour":[["family"],["friends"]],"respect":[["one another"],["friends"]]},"animals":{"eat":[["row food"]]}},
paths = data.paths(),
values = Object.keys(paths),
keystr = document.getElementById("keystr");
getPaths = function(str){
var valuesOfInterest = values.filter(f => f.includes(str));
return valuesOfInterest.reduce((p,c) => p.concat({[c]: paths[c]}),[]);
};
keystr.oninput = function(e){
console.log(JSON.stringify(getPaths(e.target.value),null,2))
}<input id="keystr" placeholder = "enter some characters" value = ""/>
因此,当您按"o“时,您将得到以下信息
[
{
"one another": [
[
"people",
"respect",
"0",
"0"
]
]
},
{
"row food": [
[
"animals",
"eat",
"0",
"0"
]
]
}
]这意味着:
["people", "respect", "0", "0"]。如果在“尊重”和“荣誉”两项下列出的“朋友”这样的多个地方列出了“彼此”,那么这个数组将包含两个带有路径的子数组。输入"fr“,自己看看。几个警告词:我们在使用对象原型时应该谨慎。我们的修改应该有描述符enumerable = false,否则它将在for in循环中列出,例如,jQuery将无法工作。(这是多么愚蠢的jQuery,因为很明显他们并没有在他们的for in循环中进行hasOwnProperty检查)一些好的读取是这里和这里,所以我们必须用Object.defineProperty()添加这个对象方法来使它成为enumerable = false;。但是为了简单起见,为了保持问题的范围,我还没有在代码中包含这个部分。
发布于 2016-06-21 21:26:04
使用这个软件包是因为流星是很棒的https://atmospherejs.com/matteodem/easy-search
https://stackoverflow.com/questions/37934725
复制相似问题