基于另一个数组的对象的打字稿过滤器数组

时间:2019-05-16 11:20:45

标签: javascript arrays typescript for-loop

我有一个如下所示的对象数组

  readonly allItems = [
    {
      id: 0,
      title: "Item 0",
      belongsTo: 'admin'
    },
    {
      id: 1,
      title: "Item 1",
      belongsTo: 'user'
    },
    {
      id: 2,
      title: "Item 2",
      belongsTo: 'all'
    },
    {
      id: 3,
      title: "Item 3",
      belongsTo: 'user'
    },
    {
      id: 4,
      title: "Item 4",
      belongsTo: 'all'
    }
  ];

我有一个数字数组,如下所示

let selItems = [0,2,4];

我想做的是根据allItems数组过滤selItems数组 为此,我编写了以下代码,这显然是错误的。

  for(let i=0; i< this.allItems.length; i++){
      if(selItems.includes(this.allItems[i].id)){
        tempMenu.push(this.allItems[i]);
      }
      console.log(tempMenu);
    }

我得到以下输出

[{
      id: 0,
      title: "Item 0",
      belongsTo: 'admin'
}]

我期望的结果是这样的:

  [
    {
      id: 0,
      title: "Item 0",
      belongsTo: 'admin'
    },
    {
      id: 2,
      title: "Item 2",
      belongsTo: 'all'
    },
    {
      id: 4,
      title: "Item 4",
      belongsTo: 'all'
    }
  ]

有人可以告诉我正确的方法吗? 谢谢!

1 个答案:

答案 0 :(得分:4)

您可以改用"//div[contains(@class,'mat-select-value')][contains(text(),'UniqueTextID')]"

.map

要将计算复杂度降低到const allItems = [{ id: 0, title: "Item 0", belongsTo: 'admin' }, { id: 1, title: "Item 1", belongsTo: 'user' }, { id: 2, title: "Item 2", belongsTo: 'all' }, { id: 3, title: "Item 3", belongsTo: 'user' }, { id: 4, title: "Item 4", belongsTo: 'all' } ]; const selItems = [0, 2, 4]; const output = selItems.map(num => allItems.find(({ id }) => id === num)); console.log(output);而不是O(N),可以先将其转换为由O(N^2)索引的对象:

id

或使用const allItems = [{ id: 0, title: "Item 0", belongsTo: 'admin' }, { id: 1, title: "Item 1", belongsTo: 'user' }, { id: 2, title: "Item 2", belongsTo: 'all' }, { id: 3, title: "Item 3", belongsTo: 'user' }, { id: 4, title: "Item 4", belongsTo: 'all' } ]; const selItems = [0, 2, 4]; const allItemsById = allItems.reduce((a, item) => { a[item.id] = item; return a; }, {}); const output = selItems.map(num => allItemsById[num]); console.log(output);

filter

相关问题