考虑下面的关联数组:
{
"body": [
{
"key1": "value1",
"body2": {
"key2": "value2"
}
}
]
}
如何搜索此数组的粗略结构?例如,我怎么说array[key1]
低于array[key2]
?如果措辞不正确,我会道歉。
答案 0 :(得分:1)
工作小提琴:http://jsfiddle.net/4gy417o7/1/
objLevels = [];
function assignLevel(obj,level){
var tempArr = objLevels[level] || [];
for(var p in obj){
if(obj.hasOwnProperty(p))
tempArr.push(p);
if(typeof obj[p]=='object')
assignLevel(obj[p],(level+1));
objLevels[level] = tempArr;
}
}
assignLevel(yourObj,1);
console.log(objLevels);
通过使用原始对象和level = 1启动递归函数assignLevel
,您应该得到一个对象数组(objLevels
),其中每个对象的键是嵌套级别,并且value是对象中处于该嵌套级别的键的数组。
所以objLevels就像
[
{1: ["body"] },
{2: [0] }, // this is because body is an array, and the object inside it is at index 0
{3: ["key1","body1"] },
{4: ["key2] }
]
然后你基本上可以找到任何特定的key
变量的嵌套级别,如下所示:
function getKeyLevel(key){
for(var level in objLevels)
if(objLevels[level].indexOf(key) > -1)
return level;
return false;
}
console.log(getKeyLevel("key2")) // 4
console.log(getKeyLevel("key1")) // 3
答案 1 :(得分:0)
您应该可以使用递归函数来执行此操作,例如
function searchObject(object, level, parent){
// If the parent is omitted, we're at the start of the search.
var obj = object[parent] || object;
// For every key of the object supplied...
Object.keys(obj).forEach(
function(key){
alert(key+" found at level "+level+".");
// Check if object exists, then if it is of type Object
if(obj[key] !== undefined && obj[key].toString() === "[object Object]"){
// Search the object at a lower level
searchObject(obj[key], level+1, key);
}
}
);
}
Here's a fiddle显示它的实际效果。
玩得开心!