这是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": [
我知道如何获取第一个对象(例如"objectId": "ueCCX8v4Qz"
):
_.where(tree, {"objectId": "ueCCX8v4Qz"})
但我不知道如何获得"objectId": "TIdm6sG1r0"
(pano:
内数组内的对象)。
如何做到这一点?
答案 0 :(得分: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>
&#13;