Find index of object in javascript using its property name

人走茶凉 提交于 2020-03-26 06:38:33

问题


I want to find Index of javascript array of objects using objects property name. My code is :-

const checkbox = [{'mumbai': true},{'bangalore': true},{'chennai': true},{'kolkata': true}];


How can i find index of chennai? Can i acheive using lodash?


回答1:


You can use .findIndex()

const checkbox = [
  {'mumbai': true},
  {'bangalore': true},
  {'chennai': true},
  {'kolkata': true}
];

const finder = (arr, key) => arr.findIndex(o => key in o);

console.log(finder(checkbox, 'chennai'));
console.log(finder(checkbox, 'kolkata'));
console.log(finder(checkbox, 'delhi'));



回答2:


checkbox.map((v,i) => Object.keys(v).indexOf("chennai") !== -1 ? i : -1).filter(v => v !== -1)[0]

Will give you the index of "chennai", replace it with any other key to get a different index.

What this does is:

  • Map the array to an array indicating only indices which contain objects with the wanted key
  • Filter only the indices which you want
  • Get the first one (you can use the rest as well if there are multiple entries matching your search)

This works in every browser since it only uses .map() , Object.keys() and .filter()



来源:https://stackoverflow.com/questions/54665358/find-index-of-object-in-javascript-using-its-property-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!