0

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.

2 Answers2

0

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>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
-1

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);
DHRUV GUPTA
  • 2,000
  • 1
  • 15
  • 24