0

I have a small problem regarding Array to find Elements using find() with findIndex. I have demo code which is worked when I am using only find() method with my array variable.

    var a = [{
      _id: 'newlead',
      count: 45
    }, {
      _id: 'contact',
      count: 12
    }, {

    leadCount: [{
          _id: 'newlead',
          count: 45
        }, {
          _id: 'contact',
          count: 12
        }]
    }]

var findElement = a.find(a => {
  return a._id === 'newlead'
});

console.log(findElement);

The actual problem is I want to check in an array, 'leadCount' is exist or not, if exist then I am doing this, I have a code. this code throws an error "TypeError: a.findIndex(...).find is not a function

let data = a.findIndex( element => {
  return 'leadCount' in element
}).find(e => {
    return e._id === 'newlead'
})

console.log(data)

Please suggest me the right thing.

thank you

3
  • Why are you using findIndex instead of find? Commented Jun 28, 2018 at 10:32
  • What output are you looking for? Commented Jun 28, 2018 at 10:33
  • I need this object inside data variable { _id: 'newlead', count: 45 } Commented Jun 28, 2018 at 10:35

1 Answer 1

3

You can try this:

 var a = [{
  _id: 'newlead',
  count: 45
}, {
  _id: 'contact',
  count: 12
}, {

leadCount: [{
      _id: 'newlead',
      count: 45
    }, {
      _id: 'contact',
      count: 12
    }]
}];



let data = a.find(e => 'leadCount' in e) || {leadCount: []}.leadCount.find(e => e._id === 'newlead')

console.log(data)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.