使用选择键创建条件子集数组

时间:2018-03-14 23:22:15

标签: javascript

我正在尝试创建数组的条件子集。

我有一个数组allBooks,其中包含typeauthorid等属性。

在特定视图中,我只想显示一些基于条件的属性。 例如;显示库存中所有书籍的汇总属性。

以下是我的尝试:

let booksInStock: any[] = [];

this.allBooks.forEach(book => {
// Add only when book is in stock
if (book.isInStock) {
    // Get only few keys from all the available keys
    let temp: any = {
      typeOfBook: book.targetType,
      author: book.author,
      bookId: book.id,
      bookDisplayName: book.value,
      bookName: book.bookName
    };
    // Add to the summarized or filtered list
    booksInStock.push(temp);
  }
});

有更有效的方法吗?

2 个答案:

答案 0 :(得分:0)

使用filtermap会更加语义化,如下所示:

let booksInStock = this.allBooks
  .filter(book => book.isInStock)
  .map(book => ({
      typeOfBook: book.targetType,
      author: book.author,
      bookId: book.id,
      bookDisplayName: book.value,
      bookName: book.bookName
      })
  );

如果效率是您的首要任务,那么for循环会更快。请参阅此链接以获取示例:https://jsperf.com/map-vs-for-loop-performance/6

答案 1 :(得分:0)

例如:

// This function is pretty generic, you can find one in e.g. underscore.js or Ramda:
const pluck = fields => item =>
  Object
    .keys(item)
    .filter(key => fields.includes(key))
    .reduce((result, key) => {
      result[key] = item[key]
      return result
    }, {})

// Create filter+map+pluck -settings for different 'views':
const inStock = books => 
  books.filter(b => b.isInStock)
    .map(pluck(['targetType', 'author', 'id', 'value', 'name']))

// Invoke them:
const booksInStock = inStock([
  { isInStock: true, author:'harry', otherFIeld:'not-included' },
  { isInStock:false, author:'notharry'}
])