gpt4 book ai didi

javascript - JS - 将键从一个对象移动到另一个对象

转载 作者:行者123 更新时间:2023-11-28 10:36:36 26 4
gpt4 key购买 nike

我有书籍 list :

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}]

当我将新书添加到 myBooks 时,我每次都会用 for 循环调用函数

最佳答案

或者,您可以使用Array.reduce ( see MDN ),例如:

const 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","author":"Sofokles"} ];

const authorFreqs = Object.entries(
myBooks
.reduce( (accumulator, value) =>
( {...accumulator, [value.author]: accumulator[value.author]
? accumulator[value.author] + 1
: 1} ),
{}) )
.map( ([key, value]) => ({ [key]: value }) );

console.log(authorFreqs);
.as-console-wrapper { top: 0; max-height: 100% !important; }

关于javascript - JS - 将键从一个对象移动到另一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60509539/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com