2015-12-02 27 views
0

這是JSON:如何使用_.where通過ID查找嵌套在對象數組中的對象?

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": [ 

我知道如何獲得第一對象(例如"objectId": "ueCCX8v4Qz"):

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

但我不知道如何獲得,例如,"objectId": "TIdm6sG1r0"pano:中的數組內的對象)。

如何做到這一點?

+0

是不是你想要的父對象返回或只是您正在搜索的對象的全景? – Quince

+0

@Quince我需要兩者(但我只關注這個問題中的pano對象)。 – alexchenco

+0

實際上只是看到了有關製作嵌套findWhere可能更合適的答案http://stackoverflow.com/a/21601628/2737978 – Quince

回答

1

可以使用reduce的組合以及在哪裏通過父元素並在指定的屬性上執行where。像

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>

相關問題