Reputation: 910
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.
Upvotes: 0
Views: 80
Reputation: 474
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});
Upvotes: 0
Reputation: 1307
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.
Upvotes: 3