英文:
Want to filter and map an array with an id
问题
I have an array,
let arr = [
{ id: "225", name: "jin" },
{ id: "226, 228", name: "villy" },
{ id: "225", name: "lil" },
{ id: "202,236,289", name: "kill" }
]
I stored an ID in a variable called testid
. I want to filter my array arr
to find the object with the matching testid
. For example, if testid
is 228, I want to find the object {id: "226, 228", name: "Villy"}
. Could you please help me resolve this issue? I've tried using map
and filter
, but I'm encountering some confusion.
Here's the code I've attempted, but it's giving different results each time for different testid
:
{this.state.testid && arr && arr.filter((dd) => (dd.id.split(", ").map((d) => d === this.state.testid)))}
英文:
I'm in little bit confusion in my code. I have an array,
let arr = [{id:"225",name:"jin"},
{id:"226, 228",name:"villy"},
{id:"225",name:"lil"},
{id:"202,236,289",name:"kill"}]
I stored an ID in a variable called testid
. I want to filter my array "arr"
which holds the "testid"
. My testid
, for example, is 228. So I want this object from the array with the {id:"226, 228", name: "Villy"}
. Could you please assist me in resolving this problem? I use map and filter out everything, but there is some confusion.
This is the code that I tried, every time sae result is coming as result for different testid
{this.state.testid && arr && arr.filter((dd) =>(dd.id.split(", ").map((d) => d === this.state.testid)))
答案1
得分: 2
如果你想要获得单个对象,可以使用 find
。
你可以创建一个函数,该函数接受数组和测试ID,并返回找到的对象:
const findTestId = (arr, testId) => {
return arr.find((i) => i.id.includes(String(testId)))
}
要获得包含找到的对象的数组,你可以使用 filter
来完成:
const filterTestId = (arr, testId) => {
return arr.filter((i) => i.id.includes(String(testId)))
}
英文:
If you want a single object, you can use find
.
You can create a function that takes the array and the test id, and returns the found object:
const findTestId = (arr, testId) => {
return arr.find((i) => i.id.includes(String(testId)))
}
To get an array with the found objects, you can do the same with filter
:
const filterTestId = (arr, testId) => {
return arr.filter((i) => i.id.includes(String(testId)))
}
答案2
得分: 0
arr[arr.findIndex(item => item.id === tested)]
英文:
First we can find the index of array then you can reach your data with it
arr[arr.findIndex(item => item.id === tested)]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论