简体   繁体   中英

How to get parent object value by using child array key value using Angular.js/Javascript

I need one help. I need to retrieve the parent object value if any child key value is there using Angular.js or Javascript. I am explaining my code below.

$scope.data = [{
    "parentdes": "Parent description1",
    "parent_id":"1"
    "childdes": [{
      "des": 'chile description11',
      "sub_id":"11"
      "subchilddes": [{
        "des": 'subchild des111',
        "sub_sub_id":"111"
      }]
    }, {
      "des": 'chile description12',
      "sub_id":"12"
      "subchilddes": [{
        "des": 'subchild des112',
         "sub_sub_id":"112"
      }]
    }]
  }, {
    "parentdes": "Parent description2",
    "parent_id":"2"
    "childdes": [{
      "des": 'chile description21',
      "sub_id":"21"
      "subchilddes": [{
        "des": 'subchild des212',
        "sub_sub_id":"212"
      }]
    }, {
      "des": 'chile description22',
      "sub_id":"22"
      "subchilddes": [{
        "des": 'subchild des222',
        "sub_sub_id":"222"
      }]
    }]
  }];

Here I have one abject which has value like parent->child->subchild means there are three level. Here suppose I have the id sub_sub_id:222 in this case I need to fetch its parent obeject value ie- $scope.data[1]['childdes'][1] and also parent to parent object value ie-$scope.data[1] .Here I need both the parent object index and by using that index the object value using Angular.js/Javascript. Please help.

You'll probably need to write a function which starts to check from the top for it's child elements. If the structure of your data does not change, ie if $scope.data is always an array, similarly, if subchilddes is also an array, then your code could be straight forward.

Otherwise, you'll have to see whether the next element is object or array.

Your code could go like this.

  1. start from $scope.data
  2. if $scope.data is an array,
  3. then for each element of array,
  4. do, check element,
  5. isString? isArray? isObject
  6. if isString
  7. if element's value is equal to your value,
  8. print the trace (you'll have to save this in earlier steps).
  9. else, if not isString, go back to step 2.

If you can come up with some code, I might be able to help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM