0

This is the JSON:

tree.json:

[
  {
    "objectId": "o3mH2lo8wO",
    "name": "Coeptis",
    "thumbnailUrl": "https://storage.googleapis.com/bundle_asia_dra/portal/buildingImg/Coeptis.png",
    "createdAt": "2015-06-29T08:16:51.897Z",
    "version": 0,
    "pano": []
  },
  {
    "objectId": "ueCCX8v4Qz",
    "name": "Sunflower",
    "thumbnailUrl": "https://storage.googleapis.com/bundle_asia_dra/portal/buildingButton/caisa.png",
    "createdAt": "2015-08-25T12:11:02.235Z",
    "version": 0,
    "space": "56-139",
    "pano": [
      {
        "objectId": "TIdm6sG1r0",
        "name": "D0",
        "panoData": [

I know how to get the first objects (e.g. "objectId": "ueCCX8v4Qz"):

 _.where(tree, {"objectId": "ueCCX8v4Qz"})

But I don't know how to get, for instance, "objectId": "TIdm6sG1r0" (the objects inside the array inside pano:).

How to accomplish that?

alexchenco
  • 53,565
  • 76
  • 241
  • 413
  • Is it that you want the parent object returned or just the pano object that you are searching for? – Quince Dec 02 '15 at 09:55
  • @Quince I need both (but I'm just focusing on the pano object in this question). – alexchenco Dec 02 '15 at 09:56
  • actually just seen this answer about making a nested findWhere which might be more appropriate http://stackoverflow.com/a/21601628/2737978 – Quince Dec 02 '15 at 10:25

1 Answers1

1

Could use a combination of reduce and where to go through the parent elements and perform a where on a specified attribute. something like

var tree = [{
  "objectId": "o3mH2lo8wO",
  "name": "Coeptis",
  "thumbnailUrl": "https://storage.googleapis.com/bundle_asia_dra/portal/buildingImg/Coeptis.png",
  "createdAt": "2015-06-29T08:16:51.897Z",
  "version": 0,
  "pano": []
}, {
  "objectId": "ueCCX8v4Qz",
  "name": "Sunflower",
  "thumbnailUrl": "https://storage.googleapis.com/bundle_asia_dra/portal/buildingButton/caisa.png",
  "createdAt": "2015-08-25T12:11:02.235Z",
  "version": 0,
  "space": "56-139",
  "pano": [{
    "objectId": "TIdm6sG1r0",
    "name": "D0",
    "panoData": []
  }]
}];


// register new function to be run on underscore
_.mixin({
  'nestedWhere': function(parent, childTarget, searchOptions) {
    
    // reduce the parent with an intial state set to an empty array that we push a parent
    // to if a child where clause is matched
    return _.reduce(parent, function(memo, parentElement) {
      if (_.where(parentElement[childTarget], searchOptions).length > 0) {
        memo.push(parentElement);
      }
      return memo;
    }, []);
  }
});


var data = _.nestedWhere(tree, "pano", {
  "objectId": "TIdm6sG1r0"
});

console.log(data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
Quince
  • 14,790
  • 6
  • 60
  • 69