![](/img/trans.png)
[英]How to get array object in nested array of array of objects javascript
[英]how to get object by passing id in an array of nested objects JavaScript
示例数据:
var data = [
{a:{id: "1",name: "alex",class: "1"}},
{a:{id: "2",name: "john",class: "2"}},
{a:{id: "3",name: "ketty",class: "3"}}
]
如果我将 id 作为 1 个结果传递:[{name:"john",class:"1"}]。
请帮我解决上述问题。
您可以使用_.find()
获取a.id
路径等于您要查找的id
项目。 然后使用_.get()
将项目从a
属性中取出,并省略id
。
注意:这将为您提供单个项目,而不是单个项目的数组。 如果你绝对需要它,你总是可以将它包装在一个数组中。
const { flow, find, get, omit } = _ const fn = id => flow( arr => find(arr, ['a.id', id]), // find the item which has the id item => get(item, 'a'), // extract it from a item => omit(item, 'id'), // remove the id ) const data = [{"a":{"id":"1","name":"alex","class":"1"}},{"a":{"id":"2","name":"john","class":"2"}},{"a":{"id":"3","name":"ketty","class":"3"}}] const result = fn('1')(data) console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
使用 lodash/fp 您可以只声明迭代对象(您希望使用的属性),因为 lodash/fp 函数是柯里化的,并且首先迭代:
const { flow, find, get, omit } = _ const fn = id => flow( find(['a.id', id]), get('a'), omit('id'), ) const data = [{"a":{"id":"1","name":"alex","class":"1"}},{"a":{"id":"2","name":"john","class":"2"}},{"a":{"id":"3","name":"ketty","class":"3"}}] const result = fn('1')(data) console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
做起来真的很简单:-
var data = [
{a:{id: "1",name: "alex",class: "1"}},
{a:{id: "2",name: "john",class: "2"}},
{a:{id: "3",name: "ketty",class: "3"}}
]
let idToFind = 1;
let filtered = data.filter(f=>f['a']['id']==idToFind);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.