它不像“导航”那么简单。以下函数将遍历对象并提供您可以用来实现您想要的东西..例如名称、值、类型、子项数量和深度。
还可以在下面查看您的案例的具体示例
主要功能
您只需像这样称呼它:loopThrough(items)并查看您的控制台了解详情。
function loopThrough(obj, depth) {
if (typeof(depth) === "undefined") {
depth = 0; // depth 0 means the "root" of your object
} else {
depth++ // increase depth if exist... depth 1 means a property of an object on depth 0
}
for (keyName in obj) {
let thisObj = obj[keyName] //value of this object
let type = thisObj.constructor.name // type: Array, Object, String, Number or Function...
if (type === "Object" || type === "Array") { // to check if this object "have children" to loop through
let childCount = type === "Object" ? Object.keys(thisObj).length : thisObj.length
console.group(depth + " (" + type + ") " + keyName + " : " + childCount) // starts a collapsable group called: depth, type and key
loopThrough(thisObj, depth) //loop through the child object
console.groupEnd() // closes the group
} else { // doesn't have children (a String, Number or Function)
console.log(depth + " (" + type + ") " + keyName + " : " + thisObj) // types: depth, type key and value
}
}
}
示例
这是一个针对 _id:3 的示例,在此示例中,我向想要的键添加了一个兄弟。
loopThrough(items, "_id", 3)
function loopThrough(obj, wantedKey = "", wantedValue = "", depth) {
if (typeof(depth) === "undefined") {
depth = 0;
} else {
depth++
}
for (keyName in obj) {
let thisObj = obj[keyName]
let type = thisObj.constructor.name
if (type === "Object" || type === "Array") {
let childCount = type === "Object" ? Object.keys(thisObj).length : thisObj.length
loopThrough(thisObj, wantedKey, wantedValue, depth)
}
if (keyName === wantedKey && thisObj === wantedValue){
siblings = Object.keys(obj)
console.log('%c Hello!, I am ' + wantedKey +":"+ wantedValue, 'color: green');
console.log('%c I have '+ siblings.length + " siblings: " + siblings.toString(), 'color: green');
console.log("%c adding a new sibling...", 'color: grey')
obj["new_sibling"] = "new_sibling_value" // add a sibling to _id 3
siblings = Object.keys(obj)
console.log('%c now I have '+ siblings.length + " siblings: " + siblings.toString(), 'color: green');
console.log('%c I am at depth ' + depth, 'color: blue');
console.log('%c it should be simple to find a way to get my parent _id at depth ' + (depth - 1) , 'color: blue');ParentID
console.log(JSON.stringify(items, null, 4));
}
}
}
如您所见,这不是一项简单的任务,但只要有一些创造力,就完全可以做到,祝您好运。