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.
2 Answers 2
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.
Comments
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});
var index = Obj.findIndex(x => typeof x.CData !== 'undefined');.In the above case it is difficult to guess why you're getting -1