-1
     const data = [
  {
    date: "2021-05-17",
    meals: [{ name: "jon", breakFast: 1, lunch: 2, dinner: 2 }],
  },
  {
    date: "2021-05-17",
    meals: [{ name: "Bob", breakFast: 3, lunch: 4, dinner: 5 }],
  },
  {
    date: "2021-05-18",
    meals: [{ name: "Boo", breakFast: 3, lunch: 4, dinner: 5 }],
  },
];

I have an array of objects. There has different date and meals(array of objects). Is it possible to show all same date meals together?

Like this one.

  const data = [
  {
    date: "2021-05-17",
    meals: [
      { name: "jon", breakFast: 1, lunch: 2, dinner: 2 },
      { name: "Bob", breakFast: 3, lunch: 4, dinner: 5 },
    ],
  },
  {
    date: "2021-05-18",
    meals: [{ name: "Boo", breakFast: 3, lunch: 4, dinner: 5 }],
  },
];
soykot2910
  • 101
  • 1
  • 8
  • Does this answer your question? [How to group an array of objects by key](https://stackoverflow.com/questions/40774697/how-to-group-an-array-of-objects-by-key) – evolutionxbox Aug 17 '21 at 14:14

2 Answers2

2

const data = [{
        date: "2021-05-17",
        meals: [{
            name: "jon",
            breakFast: 1,
            lunch: 2,
            dinner: 2
        }],
    },
    {
        date: "2021-05-17",
        meals: [{
            name: "Bob",
            breakFast: 3,
            lunch: 4,
            dinner: 5
        }],
    },
    {
        date: "2021-05-18",
        meals: [{
            name: "Boo",
            breakFast: 3,
            lunch: 4,
            dinner: 5
        }],
    },
];

let res = {};
data.forEach(x => {
    if (!res[x.date]) {
        res[x.date] = {
            ...x
        };
    } else {
        res[x.date].meals = [...res[x.date].meals, ...x.meals];

    }
});

console.log(Object.values(res));
Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
1

You need to iterate all the data and search if the result array contains the date. If not, create the new item with the date. Then just push the meals data inside.

const data = [{date: "2021-05-17",meals: [{ name: "jon", breakFast: 1, lunch: 2, dinner: 2 }],},{date: "2021-05-17",meals: [{ name: "Bob", breakFast: 3, lunch: 4, dinner: 5 }],},{date: "2021-05-18",meals: [{ name: "Boo", breakFast: 3, lunch: 4, dinner: 5 }],},];

const result = [];
data.forEach(d => {
  let i = result.findIndex(e => e.date === d.date) + 1 
  || result.push({date: d.date, meals: []});
  result[i - 1].meals.push(...d.meals);
})

console.log(result);
AlexSp3
  • 2,201
  • 2
  • 7
  • 24