首页 > 解决方案 > 在解构项目和解构行为后创建一个新数组

问题描述

我正在从服务返回一个 observable,我想创建一个新数组;

stackblitz代码在这里

allCodesAndIds: Option[] = [];

服务电话

  getAllItems(): Observable<Item> {
    return of(this.jsonData);
  }

通过以下方式解构项目

  getAllItems() {
    const items$ = this.service.getAllItems();
    items$.pipe().subscribe(res => {
      const [id, code] = res.items;
      console.log(id, code);
    });
  }

我希望我的allCodesAndIds数组如下所示

[
  {
    id: 1,
    descp: "item 1"
  },
  {
    id: 2,
    descp: "item 2"
  },
  {
    id: 3,
    descp: "item 3"
  },
  {
    id: 4,
    descp: "item 4"
  },
  {
    id: 5,
    descp: "item 5"
  }
]

此外,当前的 console.log 仅打印 2 项

{id: 1, descp: "item 1", code: "code1"}
{id: 2, descp: "item 2", code: "code2"}

而我期待它返回所有 5 个项目。有人可以解释一下这背后的原因。请。

感谢您的时间和帮助!

标签: angulartypescript

解决方案


如果我理解正确,您想像这样解构您的项目:

const items = res.items.map(({id, descp}) => ({id, descp});

这被称为object destructuring

在您的代码段中,您没有使用对象解构,而是使用array destructuring. 这会从您的项目列表中获取第一个和第二个项目。

const [item1, item2] = res.items;

数组解构也有它的用例,例如分离列表的头部和尾部,这对递归算法很有用:

const [first, ...rest] = res.items;

推荐阅读