我有这样的数据和功能:
const lodash = require('lodash')
var data = [
{
"nextStep": [
{
"nextStep": [
{
"nextStep": [
{
"nextStep": [],
"student": {
"name": "Alice",
"grade": 1
}
}
],
"student": {
"name": "Lisa",
"grade": 2
}
}
],
"student": {
"grade": 3,
"name": "This is GS"
}
}
],
"student": {
"grade": 4,
"name": "Paul"
}
}
]
function searchByJsonPath(path, obj, target) {
for (var k in obj) {
if (obj.hasOwnProperty(k))
if (k === target)
return path;
else if (typeof obj[k] === "object") {
var result = searchByJsonPath(path + "." + k, obj[k], target);
if (result)
return result;
}
}
return false;
}
我想获取对象中的最后一项,结果应该是
"name": "Alice",
"grade": 1
所以我叫searchByJsonPath
来获取路径,并使用lodash来获取项
test = searchByJsonPath('data', data, 'name');
但test = data.0.nextStep.0.nextStep.0.nextStep.0.student
正确的路径应为data[0].nextStep[0].nextStep[0].nextStep[0].student
请给我建议。
答案 0 :(得分:1)
您可以尝试使用recursion
来获得最深的元素
var data = [{ "nextStep": [ { "nextStep": [ { "nextStep": [ { "nextStep": [], "student": { "name": "Alice", "grade": 1 } } ], "student": { "name": "Lisa", "grade": 2 } } ], "student": { "grade": 3, "name": "This is GS" } } ], "student": { "grade": 4, "name": "Paul" }}]
function getData(obj) {
return obj.nextStep.length > 0
? getData(obj.nextStep[0])
: obj.student
}
console.log(getData(data[0]))