I have a response object that I’m wanting to extract all of the id
values out, but I’m not sure the best way to go about it…
const obj = {
"responseArray":[
{
"accounts":[
{
"products":[
{
"id":"123",
}
]
},
{
"products":[
{
"id":"456",
}
]
}
]
},
{
"accounts":[
{
"products":[
{
"id":"987",
}
]
},
{
"products":[
{
"id":"654",
}
]
}
]
}
]
}
The closest I’ve gotten is with mapping
const mapped = obj.responseArray.map(item => item?.accounts.map(acc => acc.products.map(prod => prod.id)))
// Response
// [ [ [Array], [Array] ], [ [Array], [Array] ] ]
These Array
bits do actually contain the IDs I’m after, it’s just obviously not in the format I’d like…
4
Answers
You can use flatMap to get a simple array instead of an array of arrays :
With "modern" (Chrome 69, Firefox 62, Edge 79, Opera 56, Safari 12) versions of JavaScript you can
Array.prototype.flatMap
:flatMap
takes a function that returns an array and will map all arrays of this function into one big array, which can then be further processed.I am using the forEach to get the job done.
I guess what you are looking for is something like this,
We need to use flatMap to flatten and map over the arrays: