让我们假设我有一个数组如下:
[
{
"name": "list",
"text": "SomeText1"
},
{
"name": "complex",
"text": "SomeText2",
"config": {
"name": "configItem",
"text": "SomeText3",
"anotherObject": {
"name": "anotherObject1",
"text": "SomeText4"
}
}
}
]我正在使用这个很棒的代码来获取具有特定密钥(http://techslides.com/how-to-parse-and-search-json-in-javascript)的所有对象。在我的示例中,由于文本作为键的外观,getObjects(data,'text','')将将所有节点作为对象返回。
我唯一的问题是,我需要知道返回对象在整个数组中的位置。
有什么办法可以得到吗?或者至少与数组相关联的对象的深度?
getObjects(r,'text','')[0] (name = list) ->深度1
getObjects(r,'text','')[1] (name = complex) ->深度1
getObjects(r,'text','')[2] (name = configItem) ->深度2
发布于 2015-01-30 12:41:24
你需要这样的东西:
function getObjectsDepth(obj, key, val, depth) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjectsDepth(obj[i], key, val,++depth));
} else
//if key matches and value matches or if key matches and value is not passed (eliminating the case where key matches but passed value does not)
if (i == key && obj[i] == val || i == key && val == '') { //
objects.push(depth);
} else if (obj[i] == val && key == ''){
//only add if the object is not already in the array
if (objects.lastIndexOf(obj) == -1){
objects.push(depth);
}
}
}
return objects;
}这将返回对象的深度,而不是对象本身,只是根据您想要的计数方式传递0或1作为最后一个param。如果同时需要对象和深度,则需要obj.push({'obj':obj,'depth':depth})。
发布于 2015-01-30 12:39:45
通过以下方法更改getObjects函数:
function getObjects(obj, key, val, depth) {
var objects = [];
depth = typeof depth !== 'undefined' ? depth : 0;
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
depth ++;
objects = objects.concat(getObjects(obj[i], key, val, depth));
} else
//if key matches and value matches or if key matches and value is not passed (eliminating the case where key matches but passed value does not)
if (i == key && obj[i] == val || i == key && val == '') { //
objects.push({"obj":obj,"depth": depth});
} else if (obj[i] == val && key == ''){
//only add if the object is not already in the array
if (objects.lastIndexOf(obj) == -1){
objects.push({"obj":obj,"depth": depth});
}
}
}
return objects;
} 现在你得到了深度和物体。
https://stackoverflow.com/questions/28235512
复制相似问题