[英]how to get object by passing id in an array of nested objects JavaScript
example data :示例数据:
var data = [
{a:{id: "1",name: "alex",class: "1"}},
{a:{id: "2",name: "john",class: "2"}},
{a:{id: "3",name: "ketty",class: "3"}}
]
if i pass id as 1 result : [{name:"john",class:"1"}].如果我将 id 作为 1 个结果传递:[{name:"john",class:"1"}]。
please help me with the above question please.请帮我解决上述问题。
You can use _.find()
to get an item with the path of a.id
that equals the id
you are looking for.您可以使用
_.find()
获取a.id
路径等于您要查找的id
项目。 Then use _.get()
to take the item out of the a
property, and omit the id
.然后使用
_.get()
将项目从a
属性中取出,并省略id
。
Note : This will give you a single item, and not an array of a single item.注意:这将为您提供单个项目,而不是单个项目的数组。 You can always wrap it in an array, if you absolutely need it.
如果你绝对需要它,你总是可以将它包装在一个数组中。
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>
With lodash/fp you can just state the iteratees (the properties you wish to use), since lodash/fp functions are curried, and iteratees first:使用 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>
its really simple to do:-做起来真的很简单:-
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.