const options = [
{_id: "0175", name: "Ahnaf"},
{_id: "8555", name: "Abir"},
{_id: "8795", name: "Book"},
]
now how to get index of _id = 8795 ??
It means how I can get the index number to get this object {_id: "8795", name: "Book"}
asked Dec 5, 2020 at 13:56
user14511946user14511946
2 Answers 2
You can use .findIndex
:
const options = [
{_id: "0175", name: "Ahnaf"},
{_id: "8555", name: "Abir"},
{_id: "8795", name: "Book"},
]
const index = options.findIndex(e => e._id==="8795");
console.log(index);
answered Dec 5, 2020 at 13:57
5 Comments
Majed Badawi
@taslimkd what's the issue?
Majed Badawi
You need to convert the
ObjectId
to a String
when comparing, something like: e._id.toString()
. You can research this more depending on the technology you're using3limin4t0r
@taslimkd Have you logged both values? Is the actually within the array? Or is it showing
-1
because there is no element containing the provided id? You can implicitly convert values by using ==
instead of ===
, so no reason to call toString()
.You need use combination of find and findIndex to find the index you are looking for.
const options = [
{_id: "0175", name: "Ahnaf"},
{_id: "8555", name: "Abir"},
{_id: "8795", name: "Book"},
]
const foundObj = options.find((option) => option._id === "8555")
const index = options.findIndex((option, index) => {
if(typeof foundObj !== "undefined" && option._id === foundObj._id) {
return index
}else
return null
} )
console.log('index', index);
answered Dec 5, 2020 at 15:37
Comments
lang-js