I have an array of objects as such
const aaa = [
{id: 10, val: "xx"},
{id: 27, val: "tr"},
{id: 13, val: "ut"}
]
Now, I know how to search for an object by a value of one of the properties. For example:
const bbb = aaa.find(obj => (obj.id === 27) )
The above code, bbb
would equal to {id: 27, val: "tr"}
Now, what I want is to find the index of the object with id 27. In other words, for the above bbb
object, the answer should be 1 (second item in the array)
How do I search for that.
Thank you.
I have an array of objects as such
const aaa = [
{id: 10, val: "xx"},
{id: 27, val: "tr"},
{id: 13, val: "ut"}
]
Now, I know how to search for an object by a value of one of the properties. For example:
const bbb = aaa.find(obj => (obj.id === 27) )
The above code, bbb
would equal to {id: 27, val: "tr"}
Now, what I want is to find the index of the object with id 27. In other words, for the above bbb
object, the answer should be 1 (second item in the array)
How do I search for that.
Thank you.
Share Improve this question edited Mar 8 at 2:50 Greeso asked Mar 8 at 2:44 GreesoGreeso 8,30915 gold badges56 silver badges84 bronze badges 3 |4 Answers
Reset to default 4Use Array.prototype.findIndex()
const haystack = [
{id: 10, val: "xx"},
{id: 27, val: "tr"},
{id: 13, val: "ut"}
]
const needleIndex = haystack.findIndex(obj => (obj.id === 27) );
console.log({ needleIndex });
Use the indexOf method with the object you are looking for.
let index = aaa.indexOf(bbb);
So full script would be...
const aaa = [
{id: 10, val: "xx"},
{id: 27, val: "tr"},
{id: 13, val: "ut"}
]
const bbb = aaa.find(obj => (obj.id === 27) );
let index = aaa.indexOf(bbb);
console.log(index);
const aaa = [
{id: 10, val: "xx"},
{id: 27, val: "tr"},
{id: 13, val: "ut"}
]
const index = aaa.findIndex(item => item.id === 27)
console.log(index)
Every array has a .findIndex() method, which takes a condition as an argument to search for the index of an array element. If the elements of the array are simple values, you can find the index of an element by providing a function that checks each element of the array.
let arr = ['a', 'b', 'c', 'd'];
let index = arr.findIndex(element => element === 'c'); // 2
Since your array contains objects, you need to pass a function to the .findIndex() method. This function will be executed for each element of the array (each object) during the search.
.findIndex(obj => obj.id === 27)
This expression checks, on each iteration of the search, whether the object has the key id with the value 27. If it does, the .findIndex() method will return the index of that element (object) in the array.
full code:
const aaa = [
{id: 10, val: "xx"},
{id: 27, val: "tr"},
{id: 13, val: "ut"}
];
const index = aaa.findIndex(obj => obj.id === 27);
console.log(index); // This will output: 1
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744904682a4600181.html
aaa.indexOf(bbb)
? – Lã Ngọc Hải Commented Mar 8 at 2:53