[英]What is the best way to find index of object from array of objects - javascript
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.使用上面的代码片段,我可以得到索引,但在实际实现中得到 -1,即使键也存在。 Data also similar to above only but not getting the reason.
数据也与上面类似,只是没有得到原因。
You have Array of objects which have indexes like 0, 1, 2.您有对象数组,其索引为 0、1、2。
x => x.CData
won't return anything. x => x.CData
不会返回任何东西。 So you need to find index of 'CData' as key of object inside that array.因此,您需要找到“CData”的索引作为该数组内对象的键。
Obj.findIndex(x => Object.keys(x).indexOf('CData') > -1 )
Please try this way.请尝试这种方式。 Hope this helps.
希望这可以帮助。
findIndex() method returns the index, if the function returns true, currently you are not returning anything. findIndex() 方法返回索引,如果函数返回 true,则当前您没有返回任何内容。 So modify your code like this:
var index = Obj.findIndex(x => {return x.CData});
所以像这样修改你的代码:
var index = Obj.findIndex(x => {return x.CData});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.