简体   繁体   English

从对象数组中查找对象索引的最佳方法是什么 - javascript

[英]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.

相关问题 在javascript中搜索对象数组以查找另一个数组的最佳方法是什么? - What is the best way to search an array of objects to find another array in javascript? 使用查找索引从数组中获取 object 或在 JavaScript 中的 map 的键处获取值的更快方法是什么? - What is a faster way to get an object from array using find index, or getting value at a key of a map in JavaScript? 在Javascript中创建对象数组的最佳方法是什么? - What is the best way to create an array of objects in Javascript? 在Javascript中检查对象是否为数组的最佳方法是什么? - What is the best way to check if an object is an array or not in Javascript? 从数组中删除对象的最佳方法是什么 - What is the best way to delete objects from Array 检查对象数组中的任何键是否包含来自数组数组对象的值的最佳方法是什么? - What would be the best way to check if any of the keys in an array of objects contain a value from an object of arrays array? 如何通过索引从对象数组中的对象数组中删除对象javascript - How to delete object from array of objects in array of objects javascript by index JavaScript,在给定编号的数组中查找索引间隔的最佳方法 - JavaScript, best way to find the index interval in an array with given number 在对象的javascript数组中查找下一个/上一个项目的最佳方法? - Best way to find the next/previous items in a javascript array of objects? 在javascript中更改对象数组顺序的最佳方法是什么 - What is the best way to change the order of array of objects in javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM