我有书籍清单:
let myBooks = [{"id":8,"name":"Don Quijote","author":"Cervantes"},{"id":9,"name":"Romeo and Juliet","author":"Shakespeare"},{"id":10,"name":"Hamlet","author":"Shakespeare"},{"id":11,"name":"Othello","author":"Shakespeare"},{"id":"12","nazev":"Antigona","autor":"Sofokles"}]
我需要找出如何与作者一起创建新对象,以及他们要进行多少次myBooks
这样的工作:
let authorsInMyBooks = [{"Cervantes":1},{"Shakespeare":3},{"Sofokles":1}]
我尝试了这个:
for (i = 0; i < myBooks.length; i++) {
if (myBooks[i].author in authorsInMyBooks) {
authorsInMyBooks[myBooks[i].author] += 1;
} else {
authorsInMyBooks[myBooks[i].author] = 1;
}
}
但是输出是:
[{"Cervantes":5, "Shakespeare":9, "Sofokles":1}]
当我向其中添加新书时,每次都使用for循环调用function myBooks
您需要使用一个空对象作为的初始值,authorsInMyBooks
然后用于map()
获取数组。
let myBooks = [{"id":8,"name":"Don Quijote","author":"Cervantes"},{"id":9,"name":"Romeo and Juliet","author":"Shakespeare"},{"id":10,"name":"Hamlet","author":"Shakespeare"},{"id":11,"name":"Othello","author":"Shakespeare"},{"id":"12","nazev":"Antigona","autor":"Sofokles"}]
let authorsInMyBooks = {}
for (let i = 0; i < myBooks.length; i++) {
if (authorsInMyBooks[myBooks[i].author]) {
authorsInMyBooks[myBooks[i].author] += 1;
} else {
authorsInMyBooks[myBooks[i].author] = 1;
}
}
authorsInMyBooks = Object.entries(authorsInMyBooks).map(([k, v]) => ({[k]: v}));
console.log(authorsInMyBooks)
您可以使用 reduce()
let myBooks = [{"id":8,"name":"Don Quijote","author":"Cervantes"},{"id":9,"name":"Romeo and Juliet","author":"Shakespeare"},{"id":10,"name":"Hamlet","author":"Shakespeare"},{"id":11,"name":"Othello","author":"Shakespeare"},{"id":"12","nazev":"Antigona","autor":"Sofokles"}]
const res = myBooks.reduce((ac, {author}) => {
ac[author] = (ac[author] || 0) + 1
return ac;
}, {})
const authorsInMyBooks = Object.entries(res).map(([k, v]) => ({[k]: v}));
console.log(authorsInMyBooks)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句