There are two arrays containing objects. One array includes objects with an id property that holds a list of ids, while the other array contains objects with a unique id property. The goal is to filter the ids in the second array based on the ids in the first list and retrieve the corresponding data.
const data1 = [{
name: 'A',
ids: [1, 2, 3]
}, {
name: 'B',
ids: [4, 5, 6]
}, {
name: 'C',
ids: [7, 8, 9]
}]
const data2 = [{
id: 1,
color: 'red'
}, {
id: 2,
color: 'black'
}, {
id: 3,
color: 'blue'
}, {
id: 4,
color: 'yellow'
}, {
id: 5,
color: 'green'
}, {
id: 6,
color: 'pink'
},
{
id: 7,
color: 'orange'
}, {
id: 8,
color: 'white'
}, {
id: 9,
color: 'teal'
}
]
const arrayToObject = (array) =>
array.reduce((obj, item) => {
obj[item.id] = item
return obj
}, {})
console.log(arrayToObject(data2))
const newData = data1.map(item => {
return {
name: item.name,
data: item.ids.map(i => arrayToObject(data2)[i])
}
})
console.log(newData)
Expected Output:
[
{
"name": "A",
"data": [
{
"id": 1,
"color": "red"
},
{
"id": 2,
"color": "black"
},
{
"id": 3,
"color": "blue"
}
]
},
{
"name": "B",
"data": [
{
"id": 4,
"color": "yellow"
},
{
"id": 5,
"color": "green"
},
{
"id": 6,
"color": "pink"
}
]
},
{
"name": "C",
"data": [
{
"id": 7,
"color": "orange"
},
{
"id": 8,
"color": "white"
},
{
"id": 9,
"color": "teal"
}
]
}
]
I've successfully obtained the desired output, but I believe there might be a more efficient and cleaner solution. Any recommendations would be appreciated.
P.S: I'm also open to leveraging lodash.