0

Hi I'm trying to find index of an object using key name.

This is how i tried to get index:

var Obj = [
  {
    BData: [
      {id: '1', name: 'C'},
      {id: '2', name: 'Java'},
    ]
  },
  {
    CData: [
      {ccode: '010', cname: 'US'}
    ]
  },
  {
    PData: [
      {id: '21', pname: 'pen'}
    ]
  }
];
var index = Obj.findIndex(x => x.CData);

with above snippet from out side I am able to get index, but from in actual implementation getting -1, even though key exist also. Data also similar to above only but not getting the reason.

1
  • 1
    you could try comparing it with undefined var index = Obj.findIndex(x => typeof x.CData !== 'undefined');.In the above case it is difficult to guess why you're getting -1 Commented Mar 16, 2020 at 7:35

2 Answers 2

3

You have Array of objects which have indexes like 0, 1, 2.

x => x.CData won't return anything. So you need to find index of 'CData' as key of object inside that array.

Obj.findIndex(x => Object.keys(x).indexOf('CData') > -1 )

Please try this way. Hope this helps.

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

Comments

0

findIndex() method returns the index, if the function returns true, currently you are not returning anything. So modify your code like this: var index = Obj.findIndex(x => {return x.CData});

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.