查找对象树中特定字段值的所有出现
finding all occurance of a particular field value inside object tree
我正在尝试打印字段"term"的所有出现的值..使用我编写的程序,它只返回第一次出现。有可能得到整个发生吗?
http://jsfiddle.net/AQ5WK/
var data = {
"_index": "test",
"_type": "news",
"_source": {
"partnerName": "propertyFile 9",
"relatedSources": "null",
"entityCount": "50",
"Categories": {
"Types": {
"Events": [{
"count": 1,
"term": "Time",
"Time": [{
"term": "Dec 9",
"Dec_9": [{
"count": 1,
"term": "2012"
}]
}]
}, {
"count": 4,
"term": "News",
"News": [{
"term": "Germany",
"Germany": [{
"count": 1,
"term": "Election"
}],
"currency": "Euro (EUR)"
}, {
"term": "Egypt",
"Egypt": [{
"count": 1,
"term": "Revolution"
}]
}]
}]
}
}
}};
var findDeepKey = function(obj, key){
var results = [];
if (typeof obj !== 'object') return null;
for (var k in obj) {
if (k === key) return obj[k];
}
for (var k in obj) {
if (typeof obj[k] === 'object') {
if (obj[k].length) {
for (var i = 0, il = obj[k].length; i < il; i++) {
results.push(findDeepKey(obj[k][i], key));
}
} else {
for (var kk in obj[k]) {
if (kk === key) return obj[k][kk];
results.push(findDeepKey(obj[k][kk], key));
}
}
}
}
for (var i = 0, il = results.length; i < il; i++) {
if (results[i] !== null)
return results[i];
}};
alert(findDeepKey(data, 'term'));
我正在尝试打印字段"术语"的所有出现的值
它存在于对象树的任何级别的任何地方?这是一个递归下降搜索:现场示例 |源
function findProps(name, data, results) {
var key, value;
// If we weren't given a results array, create one
if (Object.prototype.toString.call(results) !== "[object Array]") {
results = [];
}
// Is it an object (including an array)?
if (typeof data === "object") {
// Yes, loop through its properties
for (key in data) {
// Does it have an "own" property with this name?
// (I assume you only want "own" properties, not
// properties inherited from the prototype chain).
if (data.hasOwnProperty(key)) {
// Yes, get the value
value = data[key];
// Is this our property?
if (key === name) {
// Remember it
results.push(value);
}
// Recurse into the value?
if (typeof value === "object") {
// Yes
findProps(name, value, results);
}
}
}
}
// All done
return results;
}
var terms = findProps("term", data);
display("Found 'term' " + terms.length +
" time(s): " + terms.join(", "));
相关文章:
- 如何访问对象内部的“categoryIds”字段/键,该对象包含mongodb's `ObjectId(s)`数
- MongoDB-通过比较集合和对象的数组来返回现有字段的数组
- 如何创建具有默认值的JavaScript对象字段?(AngularJS模型相关)
- 如何在angularjs中传递对象字段作为指令参数
- 更新嵌套对象的多个字段
- 创建一个带有可变字段的json对象
- 对象中可选字段的流类型
- 有了字段的名称,我如何用空白数据初始化对象的未定义字段
- FilterHeader不适用于模型字段类型对象
- 访问KendoUI中Datasource过滤对象的字段
- 在jquery中,从同一对象的属性设置输入字段和标签的正确方法是什么
- 如何在初始化过程中引用同一对象内的对象字段
- 如何使用Typescript创建一个包含对象的字段的新对象
- 将一个html表转换为json对象并将其发送到php页面,该表有一个输入字段
- 编码为深度嵌套对象的 HTML 字段 json
- 在 Java 中访问 JavaScript 对象的字段
- Rails的问题,haml + javascript在字段对象的模糊
- 即使对于非空窗体,FormData对象也返回空.对于具有2个输入字段的表单,
- findAndModify,如何对文档进行操作's数组搜索对象并更改字段值
- Rally SDK 2 标签选择器是否有必填字段?对象没有方法'getContextPath'