考虑一个例子:
food : {
cheese: { taste: "delicious", smell: "smelly" },
bacon: { taste: "godly", smell: "godly" }
}
我想要一个无循环测试,看看“食物”的任何特性(奶酪和/或培根)是否具有“美味”的“味道”。
在这种情况下,是的。测试“恶心”应该导致错误,因为没有味道:“恶心”
我的问题确实围绕着一个无循环的解决方案,因为多层循环中的一百个属性 json 是不好的:(
考虑一个例子:
food : {
cheese: { taste: "delicious", smell: "smelly" },
bacon: { taste: "godly", smell: "godly" }
}
我想要一个无循环测试,看看“食物”的任何特性(奶酪和/或培根)是否具有“美味”的“味道”。
在这种情况下,是的。测试“恶心”应该导致错误,因为没有味道:“恶心”
我的问题确实围绕着一个无循环的解决方案,因为多层循环中的一百个属性 json 是不好的:(
我想要一个无循环测试,看看“食物”的任何特性(奶酪和/或培根)是否具有“美味”的“味道”。
你不能。假设您已将 JSON 反序列化为对象图,则必须有一个循环,因为您必须单独测试对象。
如果您还没有JSON.stringify将JSON反序列化为对象图(或者如果您想将该图反馈回可以使用正则表达式,例如:
if (jsontext.match(/\b"taste"\s*:\s*"godly"/) {
// ...something has a taste that is "godly"
}
请注意,在上面,我假设了有效的 JSON。您的问题没有有效的 JSON,因为taste它不在双引号中,这在 JSON 中是必需的。
我的问题确实围绕着一个无循环的解决方案,因为多层循环中的一百个属性 json 是不好的:(
那么,你需要让负责 JSON 的人重新设计它。
您可以通过循环一次来预先索引所有数据:
var tastes = {}, smells = {};
for (var prop in food) {
if (food.hasOwnProperty(prop) {
var item = food[prop];
if (!tastes[item.taste]) { tastes[item.taste] = [] };
tastes[item.taste].push(prop);
if (!smells[item.smell]) { smells[item.smell] = [] };
tastes[item.smell].push(prop);
}
}
然后,在未来,你可以:
if (tests.godly) { ... }
…这将节省您每次要查询数据时都必须循环访问数据,但您不能完全消除循环。
在这种情况下,循环是必要的。
function checkTaste(obj, keyToCheck, valToCheck) {
for (var key in obj) {
if (key === keyToCheck && obj[key] === valToCheck) {
return true;
}
}
return false;
}
checkKey(food, 'taste', 'godly');