获取对象中最后一个最深层的物品

时间:2018-11-21 11:06:07

标签: javascript lodash

我有这样的数据和功能:

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

请给我建议。

1 个答案:

答案 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]))