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"}].
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. Then use _.get()
to take the item out of the a
property, and omit the 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:
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.