I have a list of objects with every object of the form:
{
"myFilters": [
{
"isMatch": false,
"filters": [
{
"id": "aaaaaa",
"version": "v1"
},
{
"id": "kk",
"version": "v1"
}
]
}
],
"randomAttr1": null,
"randomAttr2": []
}
Assume that the above is an object from a list of objects stored in result
.
Now I want to get a list of all the versions and add it back to this object as value of a new element relevant_versions
but with a condition that the Id and version must be in the URL parameters. Here is my attempt at it:
for (let f of result) {
f.relevant_versions = f.myFilters.filter(x=>x.filters
.filter(item=>(item.id == this.$route.params.filterId && item.version == this.$route.params.version))
.map(fid => fid.version))
}
But I instead have the entire myFilters
element instead of the versions only. I think I'm close and making a simple mistake here.
How can I appropriately populate relevant_versions here?
Edit: So the output would look like
{
"myFilters": [
{
"isMatch": false,
"filters": [
{
"id": "aaaaaa",
"version": "v1"
},
{
"id": "kk",
"version": "v1"
}
]
}
],
"randomAttr1": null,
"randomAttr2": [],
"relevant_versions":["v1", "v1"]
}
A sample route is localhost:8080/filters/kk/v1
. Here kk
corresponds to this.$route.params.filterId
and v1
to this.$route.params.version
.
You don't want to filter the myFilters
object but instead (flat) map the values within to the matching versions
const result = [{"myFilters":[{"isMatch":false,"filters":[{"id":"aaaaaa","version":"v1"},{"id":"kk","version":"v1"}]}],"randomAttr1":null,"randomAttr2":[]}] this.$route = {params:{filterId:"kk",version:"v1"}} // this avoids mutating `results` const modifiedResult = result.map(f => ({ ...f, relevant_versions: f.myFilters.flatMap(({ filters }) => filters.filter(({ id, version }) => id == this.$route.params.filterId && version == this.$route.params.version ).map(({ version }) => version) ) })) console.info(modifiedResult)
.as-console-wrapper { max-height: 100% !important; }
If you do want to mutate result
, then replace the top-level map
with a forEach
or use a for..of
loop like in your question
result.forEach(f => {
f.relevant_versions = f.myFilters.flatMap(...)
})
// or
for (let f of result) {
f.relevant_versions = f.myFilters.flatMap(...)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.