wyc
wyc

Reputation: 55273

How to use _.where to find by ID an object nested in an array of objects?

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?

Upvotes: 0

Views: 266

Answers (1)

Quince
Quince

Reputation: 14990

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>

Upvotes: 1

Related Questions