获取 javascript 中嵌套对象的下一个 属性
Get next property of nested object in javascript
我一直在尝试编写一个 return 行中另一个 属性 键的函数。
假设我们有这个 JSON:
'Test123': {
'Another Test': {},
'Test some more': {
'Still testing?': {
'Yeah...': {}
},
'Never ending story': {}
}
},
例如,如果我们将 'Still testing?' 键传递给函数,它应该 return 'Yeah...',但是如果我们传递 'Yeah...',它应该 return 'Never ending story'。有人知道该由谁来做吗?我一直在尝试编写一个函数来执行此操作,但我的大脑不支持它...
let obj = {
'Test123': {
'Another Test': {},
'Test some more': {
'Still testing?': {
'Yeah...': {}
},
'Never ending story': {}
}
}
}
function nextKey(keyStr, object) {
if (!keyStr || !object || typeof object != 'object' || object.constructor.name != 'Object') {
console.log("Improper Parameter !!!")
return
}
let found = false
let answer = {}
findKey(object)
return (Object.keys(answer).length) ? answer : "";
function findKey(obj) {
for (let key of Object.keys(obj)) {
if(Object.keys(answer).length) return;
let value = obj[key]
if(key == keyStr)found = true;
else if(found) {answer.key = key; answer.value = value; return}
if (Object.keys(value).length) findKey(value)
}
}
}
console.log(nextKey('Still testing?', obj)) //{ key: 'Yeah...', value: {} }
console.log(nextKey('Yeah...', obj)) //{ key: 'Never ending story', value: {} }
我一直在尝试编写一个 return 行中另一个 属性 键的函数。
假设我们有这个 JSON:
'Test123': {
'Another Test': {},
'Test some more': {
'Still testing?': {
'Yeah...': {}
},
'Never ending story': {}
}
},
例如,如果我们将 'Still testing?' 键传递给函数,它应该 return 'Yeah...',但是如果我们传递 'Yeah...',它应该 return 'Never ending story'。有人知道该由谁来做吗?我一直在尝试编写一个函数来执行此操作,但我的大脑不支持它...
let obj = {
'Test123': {
'Another Test': {},
'Test some more': {
'Still testing?': {
'Yeah...': {}
},
'Never ending story': {}
}
}
}
function nextKey(keyStr, object) {
if (!keyStr || !object || typeof object != 'object' || object.constructor.name != 'Object') {
console.log("Improper Parameter !!!")
return
}
let found = false
let answer = {}
findKey(object)
return (Object.keys(answer).length) ? answer : "";
function findKey(obj) {
for (let key of Object.keys(obj)) {
if(Object.keys(answer).length) return;
let value = obj[key]
if(key == keyStr)found = true;
else if(found) {answer.key = key; answer.value = value; return}
if (Object.keys(value).length) findKey(value)
}
}
}
console.log(nextKey('Still testing?', obj)) //{ key: 'Yeah...', value: {} }
console.log(nextKey('Yeah...', obj)) //{ key: 'Never ending story', value: {} }