2017-02-17 105 views
0

例如内找到特定属性的对象,我有一个路径对象我如何嵌套的对象

var Paths = { 
    path1: { 
     name: 'method1', 
     get: { 
      name: 'param1', 
      id: 1 
     }, 
     post: { 
      name: 'param2', 
      id: 2 
     } 
    }, 
    path2: { 
     name: 'method2', 
     get: { 
      name: 'param1', 
      id: 3 
     }, 
     post: { 
      name: 'param2', 
      id: 4 
     } 
    } 
}; 

我想根据id的对象。

我试过这样做_.find(Paths, {get:{id:1}})但是这里的id也可以在post对象中。

我需要一些帮助来解决这个问题lodash

+1

你想要的输出是什么? – AshBringer

回答

1

的对象使用发现_.pickBy

var res = _.pickBy(Paths, function(path) { 
    return path.get.id === 1 || path.post.id === 1; 
}); 

for unknown key

var res = _.pickBy(Paths, function(path) { 
    return _.chain(path) 
     .values() 
     .some(function(val) { 
      return _.get(val, 'id') === 1; 
     }) 
     .value(); 
}); 
+0

'_.find(Paths,{:{id:1}})'我想要这样的东西。它不仅是获得或发布它可以是任何关键。感谢您的建议。 –

+0

@PunithMithra'_.pickBy(Paths,{get:{id:1}})'也可以工作 – stasovlas

+0

@PunithMithra我更新我的答案,为未知的密钥 – stasovlas

0

其实,你的代码是好的,因为它只看get,而不是post。也lodash具有matchesProperty iteratee,在这种情况下,可以做到这样:

_.find(Paths, ["get.id", 1]); 

此外,您还可以通过自定义功能进行过滤:

_.find(Paths, function(o) { return o.get.id == 2 || o.post.id == 2; }); 
+0

如果我搜索的ID不是“2”,但它在后可用。 我应该能够找到匹配id的路径。 –