Typescript 如何将对象推入数组中的对象?

Typescript 如何将对象推入数组中的对象?,typescript,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) =>

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
      })
    });
我的最终目标只是迭代我的订单,并访问与
order
对象中的
itemId
对应的
item
对象

以下是阵列的外观:

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,
         .
         .
         .
      }
    },
    {
    ...
    },
    .
    .
    .
]

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

您可以迭代今天的排序器,并将数据传输到新数组中。项目ID的示例:

newTodaysOrders[index].item.id = 10;


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

让我们假设您有一个类型
顺序
表示当前排序中的值。我们还假设要附加的项具有类型
OrderItem

您想将您的
订单
转换为

type OrderWithItem = Order & {item: OrderItem}
但是组装这些新项目的行为必须异步进行

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

首先,我们可以将异步部分转换为一组承诺

我们创建了一个
Promise

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

编辑:我的原始答案:

关于物品的价值是如何获得的,您没有告诉我们太多,但我怀疑您正在寻找类似以下内容:

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

要插入的订单项来自何处?您还没有说清楚。@spender from here
this.itemsService.find(subElement.itemId).subscribe((subRes:any)
-subRes.body是我的项目对象!为了更好地理解你的问题,我删除了我的原始答案并重新发布。你的原始答案实际上完全符合我的要求,所以非常感谢。但你的新答案实际上让我从一开始就知道了我的代码有什么问题,而且似乎是一个更好的练习,所以我会接受它!(但可能会在上面添加旧答案,然后用新答案详细说明?)@spenderI不知道
subscribe
函数的语义,但通常在我看到
subscribe
的地方,我正在寻找
取消订阅
…否则发射器的订阅数组将挂起其他孤立的侦听器(即泄漏)
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});
    })
  }));
const ordersWithItems: OrderWithItem[] = await Promise.all(promises);
const todaysOrdersWithItem = 
  todaysOrders.map(order => ({...order, item: orders[order.itemId]}))