Javascript多维数组

问题描述 投票:0回答:1

我需要一些帮助来更改此数据的多维数组:

const dataArr: any[] = [
    {
      id: 1,
      orders: [{ id: 1, order_name: "john Doe" }],
      product: {
        id: 1,
        name: "Plate",
        price: "7",
      },
      location: {
        id: 30475986,
        name: "store_1",
      },
      serial_no: "223311",
      qty: 1,
    },
    {
      id: 2,
      orders: [{ id: 2, order_name: "jane Doe" }],
      product: {
        id: 1,
        name: "Plate",
        price: "7",
      },
      location: {
        id: 30475986,
        name: "store_1",
      },
      serial_no: "223313",
      qty: 1,
    },
  ];

在这种情况下,我必须将位置内的序列号和价格分组,并且它必须是一个数组,然后位置也按订单分组。 这是我需要解决的输出:

[
    {
      id: 1,
      name: "Plate",
      orders: [
        {
          id: 1,
          order_name: "john Doe",
          location: [
            {
              id: 30475987,
              name: "store_1",
              assets: [{ serial_no: "223311", price: "7" }],
            },
          ],
        },
        {
          id: 2,
          order_name: "jane Doe",
          location: [
            {
              id: 30475987,
              name: "store_1",
              assets: [{ serial_no: "223313", price: "7" }],
            },
          ],
        },
      ],
    },
  ]
javascript arrays typescript multidimensional-array
1个回答
0
投票

你可以使用类似这样的函数来为你进行转换:

const transformData = (dataArr) => {
  const grouped = {};

  dataArr.forEach(item => {
    const productKey = item.product.id;
    const orderKey = item.orders[0].id;
    const locationKey = item.location.id;

    if (!grouped[productKey]) {
      grouped[productKey] = {
        id: item.product.id,
        name: item.product.name,
        orders: []
      };
    }

    let order = grouped[productKey].orders.find(o => o.id === orderKey);
    if (!order) {
      order = {
        id: orderKey,
        order_name: item.orders[0].order_name,
        location: []
      };
      grouped[productKey].orders.push(order);
    }

    let location = order.location.find(l => l.id === locationKey);
    if (!location) {
      location = {
        id: locationKey,
        name: item.location.name,
        assets: []
      };
      order.location.push(location);
    }

    location.assets.push({
      serial_no: item.serial_no,
      price: item.product.price
    });
  });

  return Object.values(grouped);
};

const transformed = transformData(dataArr);
console.log(transformed);
© www.soinside.com 2019 - 2024. All rights reserved.