Reputation: 321
I have data and function like this:
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;
}
I want to get the last item in object, the result should be
"name": "Alice",
"grade": 1
So I call the searchByJsonPath
to get the path and use the lodash to get an item
test = searchByJsonPath('data', data, 'name');
but test = data.0.nextStep.0.nextStep.0.nextStep.0.student
the correct path should be data[0].nextStep[0].nextStep[0].nextStep[0].student
Please advice me.
Upvotes: 0
Views: 66
Reputation: 4184
You can try recursion
like below to get the deepest element
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]))
Upvotes: 1