0

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?

2 Answers 2

2

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'));

Sign up to request clarification or add additional context in comments.

Comments

0
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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.