【问题标题】:JavaScript Object Literal - Data ManipulationJavaScript Object Literal - 数据操作
【发布时间】:2019-11-26 08:54:51
【问题描述】:

我有一个对象字面量,其中包含一组对象(它们是书籍)和方法,我需要获取具有最多“书籍”的“发布者”属性,但我不知道该怎么做。

这是我到目前为止所做的:

const Library = {
  _books: [
    {
      title: 'World of Warcraft: Cycle of Hatred',
      author: 'Keith DeCandido',
      publisher: 'Pocket Star',
      year: 2006
    }
  ],
  // Add Books Method
  addBook: function(book) {
    return typeof book === 'object' ? this._books.push(book) : console.log(`Please enter a valid book.`);
  },
  // Publisher w/ Most Books
  manyBooks: function() {
    return this._books.reduce((books, book) => book.publisher)
  }
}

// Add Books to the Library
Library.addBook({
  title: 'The Witcher: The Last Wish',
  author: 'Andrzej Sapkowski',
  publisher: 'Ciela',
  year: 2016
});

Library.addBook({
  title: 'Fire and Blood',
  author: 'George Martin',
  publisher: 'Bard',
  year: 2019
});

Library.addBook({
  title: 'Song of Fire and Ice',
  author: 'George Martin',
  publisher: 'Bard',
  year: 2001
});

// Print results in the console
console.log(`Total Books in the Library:`, Library.getBooks());
console.log(`Publisher With Most Books:`,  Library.manyBooks());

这是我的完整代码:https://repl.it/@natefr0st/Objects

【问题讨论】:

  • 请同时添加 wanred 结果。如果所有出版商的图书数量相同会怎样?

标签: javascript arrays json object ecmascript-6


【解决方案1】:

您可以按出版商对图书进行分组,然后获取图书数量最多的出版商。

const groupBy = (items, key) => items.reduce(
  (result, item) => ({
    ...result,
    [item[key]]: [
      ...(result[item[key]] || []),
      item,
    ],
  }), 
  {},
);

...

// Publisher w/ Most Books
manyBooks: function() {
    publishers = groupBy(this._books, "publisher")

    return Object.keys(publishers)
                 .reduce((a, b) => publishers[a] > publishers[b] ? a : b)
}

groupBy 可以看起来像只返回计数而不是书籍列表:

const groupBy = (items, key) => items.reduce(
  (result, item) => ({
    ...result,
    [item[key]]: (result[item[key]] || 0) + 1,
  }), 
  {},
);

manyBooks 函数获取最大书籍的出版商列表:

manyBooks: function() {
    publishers = groupBy(this._books, "publisher")
    maxCount = Math.max(...Object.values(publishers))
    return Object.keys(publishers) 
                 .filter((val) => publishers[val] == maxCount);
  }
}

【讨论】:

    【解决方案2】:

    我会首先将一个对象与每个出版商的书籍聚合起来:

    var publishers = this._books.reduce((publishers, book) => { 
       publishers[book.publisher] = (publishers[book.publisher]||0)+1;
       return publishers;
    }, {});
    

    然后您可以对该对象的键进行排序:

    var publishersByBooks = Object.keys(publishers).sort((a,b) => publishers[a] == publishers[b] ? 0 : publishers[a] > publishers[b] ? -1 : 1);
    

    这样,publishersByBooks[0] 将成为拥有最多书籍的出版商。 publishersByBooks[1] 可能有也可能没有同样多的书。你想用它做什么取决于你的实现。您可以访问publishers[publishersByBooks[0]] 以获取该出版商的图书数量。

    【讨论】:

    • 当我尝试 console.log 它console.log(`Publisher With Most Books:`, Library.manyBooks()); 它返回“出版商最多的书:未定义” 我使用的方法:manyBooks: function() { // return this._books.reduce((books, book) => book.publisher) this._books.reduce((publishers, book) => { publishers[book.publisher] = (publishers[book.publisher] || 0) + 1; return publishers; }, {}); }
    • @KevinZino:您注释掉的行有一个返回语句,现在丢失了。现在,manyBooks 没有返回任何内容。
    【解决方案3】:

    const Library = {
      _books: [
        {
          title: 'World of Warcraft: Cycle of Hatred',
          author: 'Keith DeCandido',
          publisher: 'Pocket Star',
          year: 2006
        }
      ],
      // Add Books Method
      addBook: function(book) {
        return typeof book === 'object' ? this._books.push(book) : console.log(`Please enter a valid book.`);
      },
      // Publisher w/ Most Books
      manyBooks: function() {
        return this._books.reduce((books, book) => book.publisher)
      },
      
      getBooks(){
       listOfBooks= this._books.map(element => {
          return element
        });
        return listOfBooks
        
        },    
        manyBooks(){
       listOfBooks= this._books.map(element => {
          return element.publisher
        });
        return listOfBooks
        
        }
    }
    
    // Add Books to the Library
    Library.addBook({
      title: 'The Witcher: The Last Wish',
      author: 'Andrzej Sapkowski',
      publisher: 'Ciela',
      year: 2016
    });
    
    Library.addBook({
      title: 'Fire and Blood',
      author: 'George Martin',
      publisher: 'Bard',
      year: 2019
    });
    
    Library.addBook({
      title: 'Song of Fire and Ice',
      author: 'George Martin',
      publisher: 'Bard',
      year: 2001
    });
    
    console.log(`Total Books in the Library:`, Library.getBooks());
    console.log(`Publisher With Most Books:`,  Library.manyBooks());

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 2013-03-06
      • 1970-01-01
      • 2015-06-17
      • 2016-02-24
      • 2014-05-21
      相关资源
      最近更新 更多