Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combine arrays into objects depending on elements

I have two arrays, Array 1 containing the sections, and Array 2 containing the objects, the goal is to insert the objects from Array 2 inside the objects into Array1 depending on the type (Sides or Sauces), for example: Each object from Array 2 containing the element type:Sauces should be set in an array inside the object of Array 1 with type:Sauces and so on. I tried by using the forEach function but since I’m relatively new to JavaScript I don’t know how to proceed

Array 1 (Sections)

Array [
  Object {
    "required": false,
    "type": "Sides",
  },
  Object {
    "required": true,
    "type": "Sauces",
  },
]

Array 2 (List of Objects)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Array [
  Object {
    "id": 2.01,
    "price": "1",
    "title": "Hot Sauce",   
    "type": "Sauces",       
  },
  Object {
    "id": 2.02,
    "price": 1,
    "title": "Medium Sauce",
    "type": "Sauces",       
  },
  Object {
    "id": 1.01,
    "price": 1,
    "title": "Ranch",
    "type": "Sides",
  },
  Object {
    "id": 1.02,
    "price": 1,
    "title": "Blue Cheese",
    "type": "Sides",
  },
]

this is what I’m trying to achieve:

Array [
      Object {
        "required": false,
        "type": "Sides",
        "data": [
                 Object {
                   "id": 1.01,
                   "price": 1,
                   "title": "Ranch",
                   "type": "Sides",
                 },
                 Object {
                   "id": 1.02,
                   "price": 1,
                   "title": "Blue Cheese",
                   "type": "Sides",
                 },
                ]
      },
      Object {
        "required": true,
        "type": "Sauces",
        "data":[
                 Object {
                  "id": 2.01,
                  "price": "1",
                  "title": "Hot Sauce",   
                  "type": "Sauces",       
                 },
                 Object {
                  "id": 2.02,
                  "price": 1,
                  "title": "Medium Sauce",
                  "type": "Sauces",       
                 },
               ]
      },
    ]

>Solution :

this should work for you:

arr1.forEach((a,i) => {
    a["data"] = arr2.filter(b => b.type == a.type);
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading