如何从对象数组创建对象的嵌套数组

时间:2021-05-12 08:07:08

标签: javascript arrays loops for-loop object

如何遍历这个对象数组并更改它,以便将各个菜单项嵌套在对象 menu_name 中?

const menus = [
  { menu_name: 'Entre', id:0 },
  {
    name: 'Soup',
    price: 14.99,
    id:1
  },
  {
    name: 'Chips & Salsa',
    price: 7.99,
    id:2
  },
  {
    name: 'Chicken Nuggets',
    price: 12.99,
    id:3
  },
  { menu_name: 'Sides', id:4 },
  {
    name: 'Fries',
    price: 4.99,
    id:5
  },
  {
    name: 'Drinks',
    price: 2.99,
    id:6
  },
  {
    name: 'Onion Rings',
    price: 5.99,
    id:7
  },
];

对于每个 menu_name 对象,最终结果应该如下所示,其中菜单数组嵌套在 menu_name 对象中

  {
        menu_name: 'Sides',
        menu: [
          {
            name: 'Fries',
            price: 4.99,
          },
          {
            name: 'Drinks',
            price: 2.99,
          },
          {
            name: 'Onion Rings',
            price: 5.99,
          },
        ],
      },

2 个答案:

答案 0 :(得分:4)

您可以使用 reduceobject destructuring

轻松实现此目的

const menus = [
  { menu_name: "Entre", id: 0 },
  {
    name: "Soup",
    price: 14.99,
    id: 1,
  },
  {
    name: "Chips & Salsa",
    price: 7.99,
    id: 2,
  },
  {
    name: "Chicken Nuggets",
    price: 12.99,
    id: 3,
  },
  { menu_name: "Sides", id: 4 },
  {
    name: "Fries",
    price: 4.99,
    id: 5,
  },
  {
    name: "Drinks",
    price: 2.99,
    id: 6,
  },
  {
    name: "Onion Rings",
    price: 5.99,
    id: 7,
  },
];

const result = menus.reduce((acc, curr) => {
  const { menu_name } = curr;
  if (menu_name) {
    acc.push({ menu_name, menu: [] });
  } else {
    const { name, price } = curr;
    acc[acc.length - 1].menu.push({ name, price });
  }
  return acc;
}, []);

console.log(result);

答案 1 :(得分:1)

var newMenu = [];
menus.forEach(menu=>{
  if(menu.menu_name){
      newMenu.push({...menu, menu: []})
  }else{
      newMenu[newMenu.length-1].menu.push(menu)
  }
});