I have two arrays of objects. One has an id property with a list of ids and the second has an object with a unique id property. I want to filter the ids in the second array with the first list and get the 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 did manage to achieve this, but I guess there might be a better clean and performant solution. Please advice me on that.
P.S: I am also open to using lodash.
