I'm guessing this is a basic question for anyone with experience and a logical brain, but this has stumped me for two days.
I'm trying to filter an array by states, then map just one property of the resulting array(s).
Here is my states array, which contains a subset of U.S. states:
const states = [{ state: 'AL' }, { state: 'OH' }, { state: 'PA' }]
Here is the array I want to first filter by state, and then map into a new array of just the values I need.
refData = [
{
state: 'AL',
details: [
{
code: '1A',
description: 'AL Description 1'
},
{
code: '1B',
description: 'AL Description 2'
},
{
code: '1C',
description: 'AL Description 3'
}
]
},
{
state: 'PA',
details: [
{
code: '1A',
description: 'PA Description 1'
},
{
code: '1B',
description: 'PA Description 2'
}
]
}
]
Here is my only working attempt to filter and then map, but it doesn't give me what I need:
const filteredRefData = refData
.filter((item) => (states.some(stateName => item.state === stateName.state)))
.map((item) => item.details)
What this gets me is an array of ALL the details, both code and description. What I need is JUST the description value, but no matter what I try, I can't arrive at that end result.
What I get from this map:
[
0: [
0: {code: "1A", description: "AL Description 1"}
1: {code: "1B", description: "AL Description 2"}
2: {code: "1C", description: "AL Description 3"}
],
1: [
0: {code: "1A", description: "PA Description 1"}
1: {code: "1B", description: "PA Description 2"}
]
]
What I need from this map:
[
0: [
0: "AL Description 1"
1: "AL Description 2"
2: "AL Description 3"
],
1: [
0: "PA Description 1"
1: "PA Description 2"
]
]
I tried using dynamic indexes, but that failed because any index I passed always related to the top level array, and not the nested array. I also tried the reduce method, but I found it difficult to understand how reduce works with just an object's key/value pairs.
Thank you for any help you can provide!