-4

I have two array, want to create a new array that match array1.id == array2.toyId.

Array1 = [
  {
    id: 2,
    name: 'arujn'
  },
  {
    id: 3,
    name: 'abhinav'
  }
]

Array2 = [
  {
    id: 1,
    toyId: 2,
    label: 'label456',
    type: 'text56'
  },
  {
    id: 2,
    toyId: 2,
    label: 'label22',
    type: 'text88'
  },
  {
    id: 3,
    toyId: 3,
    label: 'labe ffum',
    type: 'text35'
  },
  {
    id: 4,
    toyId: 3,
    label: 'label 8',
    type: 'text66'
  }
]

So, new array have name from array1 and label & type from array2,

That array will look like this:-

I am using javascript for this.

Array3 = [
  {
    name: 'arjun',
    newdata: [
      {
        label: 'label456',
        type: 'text56'
      },
      {
       label: 'label22',
       type: 'text88'
      }
    ]
  },
  {
    name: 'abhinav',
    newdata: [
      {
        label: 'labe ffum',
        type: 'text35'
      },
      {
       label: 'label 8',
       type: 'text66'
      }
    ]
  }
]

Please help me to solve this, Thank you in advance.

Abhi
  • 305
  • 5
  • 23
  • [`Array.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) and [`Array.filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) will be your friends ... – derpirscher Jun 17 '22 at 12:54
  • Could you please show us what have you tried? – Nick Grealy Jun 17 '22 at 12:54

1 Answers1

3

const Array1 = [
  {id: 2,name: 'arujn'},
  {id: 3,name: 'abhinav'}],
 Array2 = [
  {id: 1,toyId: 2,label: 'label456',type: 'text56'},
  {id: 2,toyId: 2,label: 'label22',type: 'text88'},
  {id: 3,toyId: 3,label: 'labe ffum',type: 'text35'},
  {id: 4,toyId: 3,label: 'label 8',type: 'text66'}];

const Array3 = Array1.map(element => ({name: element.name, newdata: Array2.filter(obj => obj.toyId === element.id).map(({label, type}) => ({label, type}) )}))

console.log(Array3);
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
wardialer
  • 490
  • 3
  • 7