How to get the key value from nested object

前端 未结 5 969
刺人心
刺人心 2020-12-06 15:32

I am having below object where I am trying to get all the id values.

[{
    \"type\": \"test\",
    \"id\": \"100\",
    \"values\": {
        \"name\": \"A         


        
5条回答
  •  半阙折子戏
    2020-12-06 16:08

    Using Object.keys

    function findProp(obj, prop) {
      var result = [];
      function recursivelyFindProp(o, keyToBeFound) {
        Object.keys(o).forEach(function (key) {
          if (typeof o[key] === 'object') {
            recursivelyFindProp(o[key], keyToBeFound);
          } else {
            if (key === keyToBeFound) result.push(o[key]);
          }
        });
      }
      recursivelyFindProp(obj, prop);
      return result;
    }
    
    
    // Testing:
    var arr = [{
        "type": "test",
        "id": "100",
        "values": {
            "name": "Alpha"
        },
        "validations": []
    }, {
        "type": "services",
        "validations": [{
            "id": "200",
            "name": "John",
            "selection": [{
                "id": "300",
                "values": {
                    "name": "Blob"
                }
            }]
        }]
    }];
    
    console.log(findProp(arr, "id"));

提交回复
热议问题