问题
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