admin管理员组文章数量:1197776
I have 2 arrays of objects. How can I get the index of the id
in the first array that matches the object in the second array that has isPrimary
set to true? Only one object in the second array will ever have isPrimary: true
.
let items= [
{
"id": 1,
"color" "red"
},
{
"id": 2,
"color": "green"
},
{
...
},
...
]
let items2= [
{
"age": 18,
"isPrimary" false
},
{
"age": 25,
"isPrimary": true
},
{
...
},
...
]
I have 2 arrays of objects. How can I get the index of the id
in the first array that matches the object in the second array that has isPrimary
set to true? Only one object in the second array will ever have isPrimary: true
.
let items= [
{
"id": 1,
"color" "red"
},
{
"id": 2,
"color": "green"
},
{
...
},
...
]
let items2= [
{
"age": 18,
"isPrimary" false
},
{
"age": 25,
"isPrimary": true
},
{
...
},
...
]
Share
Improve this question
asked Jan 23 at 18:31
noclistnoclist
1,8194 gold badges31 silver badges73 bronze badges
2
|
1 Answer
Reset to default 1If you just want to get the item in items
that has the same index as the item in items2
with isPrimary
set to true
you can use findIndex
on array to get that index, findIndex
and find
both take as an argument a callback function that will be evaluated against each element in the array, the function should return a boolean, and the first value of the array to satisfy the predicate represents by the function will be returned, or its index if using findIndex
, so
const index = items2.findIndex((obj) => obj.isPrimary);
then you can get the item by indexing the items
array
const item = items[index]
you could combine these steps by using find
on items
array and using the second argument of the callback, which is the current index, to check items
values at that index
const item = items.find((_,i)=>items2[i].isPrimary);
本文标签: typescriptFinding array index based on match from second arrayStack Overflow
版权声明:本文标题:typescript - Finding array index based on match from second array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738474158a2088764.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
isPrimary
initems2
2. useitems[indexThatYouFound]
– VLAZ Commented Jan 23 at 18:40