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

how to convert array into new array of parent children

I have restaurant data array , I should make another array by grouping items by category that belongs to , I should convert this array :

[
     {
      "category":  {
        "title": "Appetizers",
      },
      "id": 1,
      "price": "10",
      "title": "Spinach Artichoke Dip",
    },
     {
      "category":  {
        "title": "Appetizers",
      },
      "id": 2,
      "price": "10",
      "title": "Hummus",
    },

     {
      "category":  {
        "title": "Salads",
      },
      "id": 3,
      "price": "7",
      "title": "Greek",
    },
    {
      "category":  {
        "title": "Salads",
      },
      "id": 4,
      "price": "9",
      "title": "Beyn",
    }
  ]

into a new array that should be as final result like this:

  [{
    "category": "Appetizers",
    "items" : ["Spinach Artichoke Dip","Hummus"]
  },
  {
    "category" : "Salads",
    "items" :["Greek", "Beyn"]
  }
]

I can’t find how to do it could you please help

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

>Solution :

Lets say that your data is a constant called data

So you can do this:

const data = [
   {
    "category":  {
      "title": "Appetizers",
    },
    "id": 1,
    "price": "10",
    "title": "Spinach Artichoke Dip",
  },
   {
    "category":  {
      "title": "Appetizers",
    },
    "id": 2,
    "price": "10",
    "title": "Hummus",
  },

   {
    "category":  {
      "title": "Salads",
    },
    "id": 3,
    "price": "7",
    "title": "Greek",
  },
  {
    "category":  {
      "title": "Salads",
    },
    "id": 4,
    "price": "9",
    "title": "Beyn",
  }
];

const result = [];

data.forEach((item) => {
  const category = item.category.title;
  const title = item.title;

  let foundCategory = result.find((c) => c.category === category);
  if (foundCategory) {
    foundCategory.items.push(title);
  } else {
    result.push({ category, items: [title] });
  }
});

console.log(result);

Now your desired result will be stored in result

happy coding

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