如何将对象推入数组内的对象?

时间:2021-06-09 10:52:25

标签: typescript

this.todaysOrders 是一个 order 对象数组,带有一个 itemId 元素。我使用这个 id 来查找 item 对象,然后我想将它插入到 order 内的 this.todaysOrders 对象中,其中 order.itemId === item.id

    this.todaysOrders.forEach((subElement: any) => {
      this.itemsService.find(subElement.itemId).subscribe((subRes: any) => {
       // subRes.body here is the retrieved item object, to be inserted 
       // into the corresponding order object with the same itemId 
       // inside this.todaysOrders
      })
    });

我的最终目标只是迭代我的订单,并访问与 item 对象中的 itemId 对应的 order 对象。

这是数组的样子:

todaysOrders = [
    { 
      id: number,
      orderCode: string,
      element1: string,
      .
      .
      .
      itemId: number
    },
    {
    ...
    },
    .
    .
    .
]

我希望它在我完成后看起来像这样:

todaysOrders = [
    { 
      id: number,
      orderCode: string,
      element1: string,
      .
      .
      .
      itemId: number,
      item: {
         id: number,
         code: string,
         name: string,
         .
         .
         .
      }
    },
    {
    ...
    },
    .
    .
    .
]

2 个答案:

答案 0 :(得分:1)

假设您有一个类型 Order 表示 todaysOrders 中的值。我们还假设您要附加的项目的类型为 OrderItem

您想将 Order 转换为

type OrderWithItem = Order & {item: OrderItem}

但是组装这些新项目的行为必须异步发生。

因此,我们可以使用 Promises API 提供给我们的工具,以简洁易懂的方式协调异步性。

首先,我们可以将异步部分转换成一堆promise。

我们创建一个 Promise<OrderWithItem> 数组

const promises = this.todaysOrders.map((subElement: Order) => 
  new Promise<OrderWithItem>((resolve)=>{
    this.itemsService.find(subElement.itemId).subscribe((subRes: any) => {
      // subscriptions usually need to be unsubscribed, right?
      // do whatever to get your item
      // then mash it with the existing element
      resolve({...subElement, item});
    })
  }));

然后我们等待上面数组中的每个 promise 解析并...

const ordersWithItems: OrderWithItem[] = await Promise.all(promises);

当然,这需要在 async 函数的上下文中发生。

编辑:我的原始答案:

您还没有告诉我们如何获得 item 的价值,但我怀疑您正在寻找类似的东西:

const todaysOrdersWithItem = 
  todaysOrders.map(order => ({...order, item: orders[order.itemId]}))

答案 1 :(得分:0)

您的对象结构对于外部人员来说并不是很清楚。

您可以遍历 todaysOrders 并将数据传输到一个新数组中。项目 ID 示例:

newTodaysOrders[index].item.id = 10;

newTodaysOrders[index].item = { id: 10; code: 'code', ... }

可能已经是这样了。只要我们对您的对象类型等一无所知,我就无法提供更多帮助。

相关问题